我遇到了问题,我可以真正使用你的帮助。
我有一个发送动态类型的方法,我想从该类型创建一个对象,然后设置一些属性。以下是使其更清晰的代码:
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)
您可以使用TrySetMember方法。 请在此处详细了解:https://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trysetmember(VS.100).aspx
答案 1 :(得分:0)
听起来你想要的是这样的东西:
private void Foo(dynamic objectWithTypeToClone)
{
dynamic instanceOfType = Activator.CreateInstance(objectWithTypeToClone.GetType());
instanceOfType.SomeProperty = ObjectId.GenerateNewId(); //ignore the right side
}