This question has already been answered:
Hello. There is a certain IChatAttributes interface from which certain classes are inherited ( AiAttributes , NavAttributes , ContentAttributes .. - these classes are created using the Singleton pattern). There is also a class ChatAttributes which in the constructor creates instances of the heirs and puts them into its only property List<IChatAttributes> AttributesList need to write a generalized method that will retrieve from the AttributesList objects of the heir classes and return them.
I did this:
public T GetCurrentAttribute<T>() { T returnedObject = default(T); foreach (var item in AttributesList) { if (item is T) returnedObject = (T)item; else returnedObject = default(T); } return returnedObject; } Now I'm modeling the situation:
attributesList generated and contains two IChatAttributes ( AiAttributes and ContentAttributes ) ContentAttributes . Using an asynchronous method in another class, I want to extract these objects using the above generalized method:
var aiObj= await Task.Factory.StartNew(() => attribute.GetCurrentAttribute<AiRoutAttributes>()); var cntObj= await Task.Factory.StartNew(() => attribute.GetCurrentAttribute<ContentAttributes>()); as a result, data comes to cntObj not to cntObj .
Where I missed something, help me figure it out.
returnedObject, so the search result will be lost. Your code can be fixed simply by deleting the else branch inside the loop :) In my version, the conventional design is simply hidden insideOfType, well, I just showed how you can use the standard tools of the standard library. - Andrey NOP