簡體   English   中英

在 linq 中將對象轉換為 System.Type

[英]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))); 

只有兩種方法可以在不知道編譯時類型的情況下訪問某些內容的屬性/方法。 你肯定處於這種情況:

  • 反射- 很快就會變得相當麻煩,即使是基本的事情,但允許你做任何你想做的事情。
  • 動態– 使 C# 的行為類似於動態類型語言,但不允許您執行諸如訪問名稱也是動態的屬性之類的操作。

由於在您的情況下,屬性名稱也是動態的,我會說答案是否定的,當它們在編譯時未知時,沒有更好的方法來操作對象和屬性。

您最好以這樣一種方式來設計您的架構,以避免以非常動態的方式訪問對象,但是推薦特定方法的上下文太少。

你試圖做的事情沒有意義。

  • 這一行: Type multiplicityAttribute = myDll.GetExportedTypes().FirstOrDefault(..); 獲取您嘗試動態綁定的類型。
  • 然后你試圖反對它: (multiplicityAttribute)ca)

投完之后你會怎么做?

你是:

  • 試圖獲取屬性名稱?
  • 試圖獲取具有某些屬性的對象類型列表?
  • 試圖獲取某些靜態屬性的值?
  • 試圖獲取某個實例屬性的值,但您不知道定義該實例的類的名稱?

看起來您想要做的是創建一種通用的方法來檢查實際上非常具體的東西。 使用反射時,通常更容易轉向另一個方向:首先解決特定情況,然后重構為更通用的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM