【发布时间】:2010-03-12 10:41:41
【问题描述】:
我想知道 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 框架的限制?
编辑: 我问的原因是因为我想将委托传递给另一个程序集中的函数,并且不想要求其他程序集必须引用任何特定类型(我的示例中的“Foo”类)。我希望以某种方式弯曲标准 Func 代表,使其适合“???”部分。
【问题讨论】:
-
C# 也知道 var 这个词,并且会在构建时输入。
-
你知道你可以 foo.Factory
("name 1"),我想。您能否扩展您的问题以解释为什么需要使用 magic 而不是 foo.Factory ? -
你也可以写 'object' :)。对象魔法 = foo.Factory;
-
我稍微编辑了这个问题,添加了更深层次的原因,并且注意到我确实知道实例上的直接函数调用。
-
@Amby:不,你不能。您无法声明具有未封闭类型的变量。不编译:)