我不知道C#(或底层的.NET框架)是否支持某种“通用委托实例”:这是一个委托实例,它仍然有一个未解析的类型参数,在代理被解析时被调用(不是在创建委托时)。我怀疑这是不可能的,但我仍然要求它...通用委托实例
这是我想要做的一个例子,用一些“???”插入C#语法似乎不可用的地方。 (显然这个代码不能编译)
class Foo {
public T Factory<T>(string name) {
// implementation omitted
}
}
class Test {
public void TestMethod()
{
Foo foo = new Foo();
??? magic = foo.Factory; // No type argument given here yet to Factory!
// What would the '???' be here (other than 'var' :))?
string aString = magic<string>("name 1"); // type provided on call
int anInt = magic<int>("name 2"); // another type provided on another call
// Note the underlying calls work perfectly fine, these work, but i'd like to expose
// the generic method as a delegate.
string aString2 = foo.Factory<string>("name 1");
int anInt2 = foo.Factory<int>("name 2");
}
}
有没有一种方法可以在C#中实际执行此类操作?如果没有,这是语言的限制,还是在.NET框架?
编辑: 我想问的原因是因为我想委托传递给函数在其他组件,并且不希望要求不必引用任何特定类型的其他组件(以下简称“富“在我的例子中的类)。我希望以某种方式弯曲标准Func <>委托,以适应“???”部分。
C#也知道这个词var和将得到的构建类型。 – Younes 2010-03-12 10:44:11
你知道你可以foo.Factory(“名字1”),我想。你能否扩展你的问题来解释为什么你需要使用魔术而不是foo.Factory ? –
2010-03-12 10:48:51
你也可以写'对象':)。 object magic = foo.Factory; – 2010-03-12 10:54:35