2015-11-18 66 views
0

我有一个问题,我真的可以使用你的帮助。从动态类型创建动态对象

我有一个方法发送一个动态类型,我想从该类型创建一个对象,然后设置一些属性。以下是使代码更加清晰的代码:

private void Foo(dynamic type) 
    { 
     dynamic instanceOfType = Activator.CreateInstance(type); 

     //I realize that it probably doesn't make sense to create a dynamic 
     //instance of something, but if I put 'object' instead of it, then 
     //I can't set SomeProperty that is specific to my type 

     instanceOfType.SomeProperty = ObjectId.GenerateNewId(); //ignore the right side 
    } 

我希望我的问题很清楚,它很有道理。

谢谢!

+0

你为什么不使用接口? –

回答

0

这听起来像你想要的东西是这样的:

private void Foo(dynamic objectWithTypeToClone) 
{ 
    dynamic instanceOfType = Activator.CreateInstance(objectWithTypeToClone.GetType()); 

    instanceOfType.SomeProperty = ObjectId.GenerateNewId(); //ignore the right side 
}