2 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
我看不到如何在編譯時(shí)強(qiáng)制執(zhí)行此操作,但如果您對(duì)運(yùn)行時(shí)檢查沒問題,您可以這樣做:
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貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使“GetInstance”方法動(dòng)態(tài)化,以便在設(shè)置類時(shí)也設(shè)置方法。這樣你就可以在運(yùn)行時(shí)依賴泛型來獲得正確的類型。它可能看起來像這樣:
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 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)