使用Type,对象与使用SetValue的目标类型不匹配

时间:2016-05-23 12:11:23

标签: c#-4.0

我正在尝试根据用户输入文档动态构建set对象。由于某种原因,SetValue抛出Object与目标类型不匹配,尽管它确实如此。

我试图实现甚至可能吗?

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 classname = .Assembly.TestObject

1 个答案:

答案 0 :(得分: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();
        }
    }