[英]Convert object to System.Type in linq
我需要將一個對象轉換為System.Type
對象。
我讀過 C# 是靜態類型的,所以這是不可能的。
這是真的?
如果是,我怎樣才能做到這一點?
Assembly myDll = Assembly.LoadFrom(dllData.Path);
Type manyAttribute = myDll.GetExportedTypes().FirstOrDefault(...);
Type multiplicityAttribute = myDll.GetExportedTypes().FirstOrDefault(..);
//Here is the problem
propertiesOnOtherFile = propertiesOnOtherFile.Where(t =>
t.GetCustomAttributes(false).Any(ca =>
!string.IsNullOrEmpty(((multiplicityAttribute)ca).PropertyName)));
這是一行:
((multiplicityAttribute)ca).PropertyName)
有沒有其他方法可以做到這一點?
編輯:
由於很多問題,這是我的范圍:
public class PocoClass
{
[ManyAttribute]
public ObjectX MyProp;
}
ManyAttribute declaration
{
public string PropertyName;
}
ManyAttribute 位於動態加載的 DLL 中。 然后,如我上面的示例,我需要將 customAttribute (ManyAttribute) 轉換為 ManyAttribute,以便檢查 PropertyName 的值。
我仍然不明白這個......但這應該有效。
IEnumerable<Type> propertiesOnOtherFile = new List<Type>(); //from somewhere?
//Here is the problem
propertiesOnOtherFile = propertiesOnOtherFile.Where(t =>
t.GetCustomAttributes(false).Any<dynamic>(ca =>
!string.IsNullOrEmpty(ca.PropertyName)));
只有兩種方法可以在不知道編譯時類型的情況下訪問某些內容的屬性/方法。 你肯定處於這種情況:
由於在您的情況下,屬性名稱也是動態的,我會說答案是否定的,當它們在編譯時未知時,沒有更好的方法來操作對象和屬性。
您最好以這樣一種方式來設計您的架構,以避免以非常動態的方式訪問對象,但是推薦特定方法的上下文太少。
你試圖做的事情沒有意義。
Type multiplicityAttribute = myDll.GetExportedTypes().FirstOrDefault(..);
獲取您嘗試動態綁定的類型。(multiplicityAttribute)ca)
投完之后你會怎么做?
你是:
看起來您想要做的是創建一種通用的方法來檢查實際上非常具體的東西。 使用反射時,通常更容易轉向另一個方向:首先解決特定情況,然后重構為更通用的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.