With a dynamic, awkward reflection no more?

C # 4.0 introduces a keyword dynamicthat will look for runtime.

Does this mean we need an awkward reflection? If so, can you set an example?

+3
source share
3 answers

We will still have Reflection - using "dynamic" for regular CLR objects will invoke the reflection-based dispatcher.

So - we will still have Reflection, but it will be easier to do.

Here is an example:

// Via 'dynamic'    
dynamic dx = GetSomeCLRObject();
dx.DoSomething();
dx.SomeMember = 2;

// Via Reflection
object x = GetSomeCLRObject();
Type xt = x.GetType();
MemberInfo DoSomethingMethod = xt.GetMethod("DoSomething");
DoSomethingMethod.Invoke(x, null);
PropertyInfo SomeMemberProperty = xt.GetProperty("SomeMember");
SomeMemberProperty.SetValue(x, 2);

I do not know about you, but I like the first one. =)

, Intellisense, IDE, , .

+6

- Reflection. , , - - , . , .:)

, PDC , ( # 4.0).

+4

, , , , , , .

, dynamic :

  • where the method name is not known at compile time (i.e. it is loaded from config / user input)
  • object creation
  • maybe some generation scenarios

The greatest use that I see for dynamicis:

  • COM interoperability (obviously)
  • support for common operators
  • duck typing where there is no common interface
  • DLR interop (see comments)

But this definitely does not solve every reflection.

+1
source

Source: https://habr.com/ru/post/1707537/


All Articles