object obj = .... Type mytype = this.GetType(); var objType = (mytype)obj; 

This is not how it works (in object there is actually a different type of variable, but it is not known in advance, but it is known that this.GetType () always corresponds to it.

  • Suppose even you could lead a variable to a type that is not known in advance. And what will you do with it? If the type is unknown, then the operations are unknown. Tell your real task better. Why do you need it? - VladD

1 answer 1

It does not work this way, because it can only result in types known at compile time.

The dynamic type can help you. However, you must know which operations the object supports. A small example:

 class Program { static void Main(string[] args) { dynamic fooValue = Foo(); // тип возвращаемого значения заранее неизвестен Console.WriteLine(fooValue.Length); // выводит 5 dynamic barValue = Bar(); // тип возвращаемого значения заранее неизвестен Console.WriteLine(barValue.R); // выводит 255 } private static object Foo() { return "Hello"; } private static object Bar() { return Color.White; } } 

You can also use reflection and query / set the required fields / properties / call methods first by getting a reference to them using Type.GetField() / Type.GetProperty() / Type.GetMethod() , and then working using FieldInfo / PropertyInfo . GetValue() / SetValue() and MethodInfo.Invoke() (which is less convenient, of course).

  • Yes, thanks, it helped), and I’ve been to var c = TypeDescriptor.GetConverter (mytype) .ConvertFrom (obj); and even var p = Activator. CreateInstance (mytype, obj); and although the studio itself did not complain, but errors appeared in the performance - beatsspam
  • It's my pleasure. You can mark the answer as correct. - andreycha