[英]C# Reflection - Type error
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
存儲在paraObj[0]
值的類型為RuntimeParameterInfo
,而EqualsExpression
的構造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);
您沒有提供構造函數從您的代碼中期望的類型,很明顯,您正在傳遞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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.