简体   繁体   English

如何使用模板委托

[英]How to use templated delegate

I'm trying to use a templated delegate in one of my class. 我正在尝试在我的一个课程中使用模板化委托。

Here the class definition : 这里的类定义:

internal class MyClass : BaseClass
{
    public delegate T Create<T>(int identity) where T : SomeOtherClass;
    public Create<T> CreateCB {get;set;}    //<-- This here doesn't compile
}

I will use the CreateCB such as this 我将使用CreateCB这样的CreateCB

return CreateCB<InheritedClassFromSomeOtherClass>(someId);

and

return CreateCB<OtherInheritedClassFromSomeOtherClass>(someId);

etc. 等等

I can't template the whole MyClass since it will need to use the delegate to create many different type who inherit from SomeOtherClass 我无法对整个MyClass模板化,因为它将需要使用委托来创建许多继承自SomeOtherClass类型

The line who doesn't compile don't need to be a property but I still need to use my generic templated delegate. 不编译的行不必是属性,但是我仍然需要使用我的通用模板委托。 How can I do this? 我怎样才能做到这一点?

My app target .net 4 client profile 我的应用程序目标.net 4客户端配置文件

Your T is scoped to the delegate, but the T you're trying to use in the property is undefined. 您的T的作用域是委托人,但是您尝试在属性中使用的T是未定义的。

Your problem here is that there is no such thing as a generic property, therefore you can't define T . 您的问题是没有通用属性,因此无法定义T

There are two workarounds: 有两种解决方法:

  • Make the class generic, so T is defined everywhere: 使该类通用,因此T随处定义:

     internal class MyClass<T> : BaseClass where T : SomeOtherClass { public delegate T Create(int identity); // Now T is in scope public Create CreateCB { get; set; } } 
  • Use a getter/setter pair, if you really can't make the class generic, but this is... ugly : 如果确实不能使类通用,则使用getter / setter对,但这很丑陋

     internal class MyClass : BaseClass { private object _createCB; public delegate T Create<T>(int identity) where T : SomeOtherClass; public Create<T> GetCreateCB<T>() where T : SomeOtherClass; { return (Create<T>)_createCB; } public void SetCreateCB<T>(Create<T> fn) where T : SomeOtherClass; { _createCB = fn; } } 

    Hopefully this snippet shows why there's no such thing as a generic property in the first place. 希望这段代码能说明为什么一开始就没有通用属性。 You lose the strong typing anyway because of the storage. 无论如何,您会因为存储而失去强类型。 And you have to provide T explicitly on each get/set - you'd better be coherent with that. 而且您必须在每个get / set上显式提供T最好与之保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM