简体   繁体   中英

Can I get the type of a Lazy value before creating the value?

Let's say I have a class "MyClass" with a private list property set in the following way:

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

And a method on the same class:

public void OpenTab<T>();

Which I would like to call as such:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM