Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Activator.CreateInstance和使用表达式之间有明显的区别吗?_C# - Fatal编程技术网

C# Activator.CreateInstance和使用表达式之间有明显的区别吗?

C# Activator.CreateInstance和使用表达式之间有明显的区别吗?,c#,C#,使用此代码: public static class ChocolateFactory<T> { private static Func<int, int, T> Func { get; set; } static ChocolateFactory() { ChocolateFactory<EmergencyChocolate>.Func = (a, b) => new EmergencyChocolate(a,

使用此代码:

public static class ChocolateFactory<T>
{
    private static Func<int, int, T> Func { get; set; }

    static ChocolateFactory()
    {
        ChocolateFactory<EmergencyChocolate>.Func = (a, b) => new EmergencyChocolate(a, b);
    }

    public static T CreateChocolate(int a, int b)
    {
        return (T)Activator.CreateInstance(typeof(T), a, b);
        //return ChocolateFactory<T>.Func(a, b);
    }
}
公共静态类巧克力工厂
{
私有静态Func Func{get;set;}
静态巧克力工厂()
{
ChocolateFactory.Func=(a,b)=>新紧急巧克力(a,b);
}
公共静态T(int a,int b)
{
return(T)Activator.CreateInstance(typeof(T),a,b);
//返回巧克力工厂。Func(a,b);
}
}
如果我跑步:

var myChocolate=ChocolateFactory.CreateChocolate(1,2)

这两种创建方法之间是否存在显著差异(一种被注释掉)?Activator的代码更简洁,但我知道它可能会更慢,但我想知道我是否忽略了其他东西。我还想知道这里是否有预编译的内容


另外,如果不使用Activator,这里的方法的名称是什么?

对于Activator类,您可以通过只有一个方法生成任何类型的实例

使用工厂方法只能创建一个类的实例,而对于不同的类,必须创建不同的工厂方法


活化剂不比另一种清洁。这取决于你想做什么。IoC容器通常使用Activator,因为它无法为所有类创建工厂方法,因为它根本不知道您得到了什么。

如果使用
Activator.CreateInstance
,则不会进行静态检查。编译器无法检查是否存在具有两个
int
参数的公共构造函数


它可能更慢,因为它使用反射。

你能解释一下为什么
返回ChocolateFactory.Func(a,b)
只适用于一种类型?在您的示例中,您有这样一个硬编码:new Emergency Chocolate(…),这就是为什么。使用activator时,您没有对具体类的引用,您总是使用T和typeof(T),哦,我没有注意到func返回了什么。谢谢你的解释。顺便说一句,我不是问题所有者…:)