Given 1:

public abstract class BaseEntityViewModel<T> where T : RealmObject { public T SomeMethod()`; //какие-то проперти } public class SomeClass1 :RealmObject {} public class SomeClass2 :RealmObject {} 

Given 2:

 IList<T> origObjList; //List<RealmObject> -- получаю его в рантайме IEnumerator<T> currObjList; // List<BaseEntityViewModel<SomeClass>> -- получаю его в рантайме 

So here are 2 questions right away:

  1. How do I say something like:

      ((where have SomeMethod)currObjList).SomeMethod(); 

    That is, how can I tell the precompiler that I can call the SomeMethod() method without directly specifying the type? (I just don’t know it in advance, but I cannot specify the parent class or interface) Even if I receive an object as a method, it doesn’t matter.

  2. I know that I can get from given2 a value of type Т in runtime; How can I cast the result of the previous item in this T in rantayme? Considering that converting most likely will not work ... How do I record "(TypeSomeType) objectRez" when TypeSomeType is stored in someTypeVariable

  • not sure whether it is clear enough to write, if you need to correct - write - Andrew
  • 3
    The desire to ask (and get answers to) such questions is an indication that something is wrong in the Danish kingdom. - Igor
  • in my case, just an attempt to write one clever universal method. Which is already 95% written. - Andrew
  • The desire to write "tricky universal" code leads straight to hell. - Igor
  • one
    here you can use dynamic - Grundy

1 answer 1

 T result = (T)(obj.GetType().GetMethod("SomeMethod")?.Invoke(obj, null)); 
  • and about the caste in runtime (question 2)? - Andrew
  • there T is not known in advance, as was said in the question ... But I can get it into a variable so that I can later cast some tricky macaron. Imagine that you have a variable Type origType in which there is this Т - Andrew
  • Dynamically, there is the Convert.ChangeType , but the "template" is more convenient in some cases. - nick_n_a pm
  • I'm not sure whether it will work here, I will test it now, and if I note the answer as correct - Andrew
  • @Andrew I have a feeling that you understand something of your own under the word "cast". Invoke returns a reference to object . In fact, this link contains an object of a certain type, regardless of whether you apply a cast to it or not. - Igor