2 回答

TA贡献1817条经验 获得超6个赞
我看不到如何在编译时强制执行此操作,但如果您对运行时检查没问题,您可以这样做:
class Factory
{
private static Type _type;
public static void SetClass(Type t)
{
if (!(typeof(Base)).IsAssignableFrom(t))
{
throw new ArgumentException("type does not extend Base", nameof(t));
}
_type = t;
}
public static Base GetInstance()
{
return (Base)Activator.CreateInstance(_type);
}
}

TA贡献1921条经验 获得超9个赞
您可以使“GetInstance”方法动态化,以便在设置类时也设置方法。这样你就可以在运行时依赖泛型来获得正确的类型。它可能看起来像这样:
public class Factory
{
private static Func<Base> _getInstance;
//option if you want to pass in an instantiated value
public static void SetClass<T>(T newType) where T : Base, new()
{
_getInstance = () => new T();
}
//option if you just want to give it a type
public static void SetClass<T>() where T : Base, new()
{
_getInstance = () => new T();
}
public static Base GetInstance()
{
return _getInstance();
}
//you could just make GetInstance Generic as well, so you don't have to set the class first
public static Base GetInstance<T>() where T : Base, new()
{
return new T();
}
}
- 2 回答
- 0 关注
- 167 浏览
添加回答
举报