2016-05-23 164 views
0

我想基于用户输入文档动态生成设置对象。出于某种原因,SetValue抛出Object与目标类型不匹配,尽管如此。对象与SetValue使用类型不匹配的目标类型

即时尝试实现甚至可能吗?

private void MapProp(string prop, string invalue) 
    { 
      var currType = _userAssembly.GetType(_className); 

      var property = currType.GetProperty(prop, BindingFlags.Public | BindingFlags.Instance); 
      var value = Convert.ChangeType(invalue, property.PropertyType); 

      property.SetValue(styleType, value, null); 
     } 
    } 

目前其试图映射到上述目标:

public class TestObject: ITestObj 
{ 
public string PropertyA {get;set;} 
public string PropertyB {get;set;} 
} 

长途区号

MapProp("PropertyA", "testValue"); 

和类名的getType = .Assembly.TestObject

+0

您展示的不包括有关目标类型任何东西,也不是源类型的代码。我们无法帮助您基于您的收入。 – krillgar

+0

更新了更多的信息,谢谢。 – user4550364

回答

0

@ user4550364,我不知道你的_user组件做了什么,所以我会把我的示例代码,这可能会帮助你做广告将想法转化为你的代码。这也是后期绑定的一个例子。

类文件

public class TestObject: ITestObj 
{ 
public string PropertyA {get;set;} 
public string PropertyB {get;set;} 
void Print(string PropertyA,string PropertyB) 
    { 
//Assuming that interface ITestObj has this method definition and hence implementing here. 
    } 
} 

主代码

using System.Reflection; 

static void Main(string[] args) 
     { 
      Assembly executingassembly = Assembly.GetExecutingAssembly(); 

      Type TestObjecttype = executingassembly.GetType("ur_namespace.TestObject"); 

      object instance = Activator.CreateInstance(TestObjecttype); 

      string[] parameters = new string[2]; 
      parameters[0] = "PropertyA "; 
      parameters[1] = "PropertyB "; 
      //To get properties 
      PropertyInfo[] properties = TestObjecttype .GetProperties(); 
      foreach (PropertyInfo property in properties) 
       { 
      Console.WriteLine(property.PropertyType.Name+" "+property.Name); 
       } 
      MethodInfo method = customertype.GetMethod("Print"); 
      //Object created ,now invoke using its instance 
      string printMethodInvoked= (string)method.Invoke(instance, parameters); 
      Console.WriteLine(printMethodInvoked); 
      Console.Read(); 
     } 
    } 
相关问题