【发布时间】:2017-03-16 22:33:32
【问题描述】:
考虑一下这个 MCVE:
using System;
public interface IThing { }
public class Foo : IThing
{
public static Foo Create() => new Foo();
}
public class Bar : IThing
{
public static Bar Create() => new Bar();
}
public delegate IThing ThingCreator();
class Program
{
static void Test(ThingCreator creator)
{
Console.WriteLine(creator.Method.ReturnType);
}
static void Main()
{
Test(Foo.Create); // Prints: Foo
Test(Bar.Create); // Prints: Bar
Test(() => new Foo()); // Prints: IThing
Test(() => new Bar()); // Prints: IThing
}
}
为什么静态工厂方法反射返回类型给出具体类型,而内联调用构造函数给出接口?我希望它们都是一样的。
另外,有没有办法在 lambda 版本中指定我希望返回值是具体类型?还是调用静态方法是唯一的方法?
【问题讨论】:
-
静态方法并不是唯一的方法。您也可以使用非静态的。例如
Func<Foo> f = () => new Foo(); Test(f.Invoke);但真正的问题是,您为什么还要检查(可能是多播)委托实例上的.Method.ReturnType?那有什么用;你为什么在乎? -
@Jeppe - 第三方库有一个公共 API,其方法类似于
Test。我没想到通过传递 lambda 而不是对实际函数的引用会产生副作用。不得不挖掘发现他们检查了方法的返回类型。如果是我自己的代码,我不会创建这样的东西。
标签: c# .net reflection lambda delegates