0
在下面的代碼中。功能getInstance
動態創建Aaa
,Bbb
和Ccc
的實例。但是,如何動態生成Union3<...>.Case2(Bbb)
?動態返回內部類?
Union3<Aaa, Bbb, Ccc> getInstance(int i)
{
Type t = getType(i); // one of Aaa, Bbb, Ccc
var instance = Activator.CreateInstance(t);
// .... set property values
return ???? // Union3<Aaa, Bbb, Ccc>.Case?(instance) // 1 to 3 to replace the "?"
}
public abstract class Union3<A, B, C>
{
public abstract T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h);
public sealed class Case1 : Union3<A, B, C>
{
public readonly A Item;
public Case1(A item) : base() { this.Item = item; }
public override T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h)
{
return f(Item);
}
}
public sealed class Case2 : Union3<A, B, C>
{
public readonly B Item;
public Case2(B item) { this.Item = item; }
public override T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h)
{
return g(Item);
}
}
public sealed class Case3 : Union3<A, B, C>
{
public readonly C Item;
public Case3(C item) { this.Item = item; }
public override T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h)
{
return h(Item);
}
}
}
'if(i == 1)return new Case1(instance)'etc ...?不確定你在問什麼,因爲你不能返回一個新的'Union3',因爲它的摘要 –
2014-08-28 22:10:14