2016-05-23 172 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(); 
     } 
    } 
相關問題