C#反射 - 输入错误

时间:2012-01-10 13:10:18

标签: c# reflection ektron

string assembly = "Ektron.Cms.ObjectFactory.dll";
string asspath = path + "bin\\" + assembly;
Assembly run_obj = Assembly.LoadFrom(@asspath);
paraObj[0] = run_obj.GetType(
    "Ektron.Cms.Search.SearchContentProperty",
    true,
    true
).GetProperty("Language");

string equalExp = "Ektron.Cms.Search.Expressions.EqualsExpression";
Type objclass = run_obj.GetType(equalExp, true, true);       
object objObj = Activator.CreateInstance(objclass, paraObj);

Activator.CreateInstance(objclass, paraObj)会抛出错误:

  

System.Reflection.RuntimeParameterInfo无法隐式转换   进入Ektron.Cms.Search.Expresions.PropertyExpression

2 个答案:

答案 0 :(得分:1)

paraObj[0]中存储的值的类型为RuntimeParameterInfo,而EqualsExpression的构造函数需要类型为PropertyExpression的对象。您需要确保paraObj中对象的类型可以绑定到Activator的合适构造函数,以便能够实例化新对象。

要解决您的问题,您需要创建PropertyExpression的实例并将其用作paraObj数组中的第一个元素:

string assembly = "Ektron.Cms.ObjectFactory.dll";
string asspath = path + "bin\\" + assembly;
Assembly run_obj = Assembly.LoadFrom(@asspath);

PropertyInfo propertyInfo = run_obj.GetType("Ektron.Cms.Search.SearchContentProperty", true, true).GetProperty("Language");
PropertyExpression propertyExpression = new PropertyExpression(propertyInfo); // create the property expression here, I am unsure how to instantiate it.
paraObj[0] = propertyExpression;
paraObj[1] = longValue;

string equalExp = "Ektron.Cms.Search.Expressions.EqualsExpression";
Type objclass = run_obj.GetType(equalExp, true, true);       
object objObj = Activator.CreateInstance(objclass, paraObj);

答案 1 :(得分:0)

您没有提供构造函数期望从您的代码中获得的类型,很明显您正在传递PropertyInfo

如果您需要PropertyInfo所指向的属性值,则必须使用该值 PropertyInfo.GetValue

我在你的代码片段中推测(因为我没有Ektron代码),你应该做类似的事情 -

var propInfo  = run_obj.GetType(
                  "Ektron.Cms.Search.SearchContentProperty",
                   true,true).GetProperty("Language");

paraObj[0] = propInfo.GetValue(null,null)  //depending on the requirement