开发者

Initializing class fields via Emit/Reflection

Suppose I have three classes A,B and C generated via emit/reflection abilities of .NET framework, and emmiting object in following manner:

class A
{
   B someField1;
   C some开发者_Go百科Field2;
}

I need to initialize someField1 and someField2 after creating object:

A someObject;

How to do this? The someObject type is object but I have no idea how to cast it to A type created dynamically and enter fields and initialize it. Thank's in advance for help.


You cannot cast to a dynamically created type in your code, as the compiler cannot know that type.

You can do what you need in a couple of ways:

// 1 - using reflection
// these will actually be your dynamically created objects...
object a = CreateA();
object b = CreateB();
System.Reflection.FieldInfo someField1 = a.GetType().GetField(
    "someField1", 
    BindingFlags.Instance | BindingFlags.NonPublic);
someField1.SetValue(a, b);

or

// 2 - using dynamic (C# 4)
dynamic a = CreateA();
dynamic b = CreateB();
a.someField1 = b;


Just a follow up to Paolo...

If someField1 and someField2 are known at compile time (which appears to be the case) then it would be advisable to have them declared in an interface that your dynamically created class implements. That way you can simply case someObj to the interface type.

interface IObjectWithFields
{
    B someField;
    C someField;
}

object a = CreateA();
((IObjectWIthFields)a).someField1 = CreateB();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜