c# - 使用内部构造函数创建泛型类

标签 c# factory-pattern generics object-construction

是否可以在泛型方法中使用其内部构造函数构造一个对象?

public abstract class FooBase { }

public class Foo : FooBase {
   internal Foo() { }
}

public static class FooFactory {
    public static TFooResult CreateFoo<TFooResult>()
    where TFooResult : FooBase, new() {
        return new TFooResult();
    }
}

FooFactoryFoo 位于同一个程序集中。类像这样调用工厂方法:

var foo = FooFactory.CreateFoo<Foo>();

他们得到编译时错误:

'Foo' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TFooType' in the generic type or method 'FooFactory.CreateFoo()'

有什么办法可以解决这个问题吗?

我也试过:

Activator.CreateInstance<TFooResult>(); 

这会在运行时引发相同的错误。

最佳答案

您可以删除 new() 约束并返回:

//uses overload with non-public set to true
(TFooResult) Activator.CreateInstance(typeof(TFooResult), true); 

虽然客户也可以这样做。然而,这很容易出现运行时错误。

这是一个很难以安全的方式解决的问题,因为该语言不允许抽象构造函数声明。

关于c# - 使用内部构造函数创建泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3650707/

相关文章:

c++ - "Downcasting"unique_ptr<Base> 到 unique_ptr<Derived>

java - 创建方法与工厂方法

c# - 无法从 'SpecificComponent' 转换为 'IComponent<IComponentGuid>'

ios - 具有协议(protocol)问题的 Swift 通用 UIView 子类

c# linq where on object lists 非常慢

c# - Facebook/Google/Twitter 记住登录信息

c# - 如何在自己的类中调用接口(interface)方法?

c# - 依赖注入(inject)与分层架构

c# - Ninject.Extensions.Factory : cannot find binding

使用递归 Hashmap 的 Java 泛型类型安全警告