我可以在创建值之前获取Lazy值的类型吗?

c#

假设我有一个“MyClass”类,其私有列表属性设置如下:

List = new List<Lazy<BaseClass>> {
    new Lazy<BaseClass>(() => new DerivedClassA(x)),
    new Lazy<BaseClass>(() => new DerivedClassB(x, y)),
    new Lazy<BaseClass>(() => new DerivedClassC())
};

以及同一个类的方法:

public void OpenTab<T>();

我想这样称呼它:

myClassObject.OpenTab<DerivedClassA>();

Which will then set a property in MyClass with the value from the lazy instance in List which creates that type.

Is there a way that I can use the type parameter in OpenTab to ensure that I only create the value from the list of lazy instances which creates a value of the specified type?

回答

No, but you could store them in a Dictionary<Type, Lazy<Type>>

List = new Dictionary<Type, Lazy<BaseClass>> {
    [typeof(DerivedClassA)] = new Lazy<BaseClass>(() => new DerivedClassA(x)),
    [typeof(DerivedClassB)] = new Lazy<BaseClass>(() => new DerivedClassB(x, y)),
    [typeof(DerivedClassC)] = new Lazy<BaseClass>(() => new DerivedClassC())
};

public void OpenTab<T>()
{
   var instance = List[typeof(T)].Value;
   // Do whatever
}

  • To add to this: if you wanted to avoid the repitition of the type, you could define a method e.g. `void Register<T>(Func<T> factory) where T : BaseClass { dict.Add(typeof(T), new Lazy<BaseClass>(() => factory())); }` then `Register(() => new DerivedClassA(x))`, etc

以上是我可以在创建值之前获取Lazy值的类型吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>