簡體   English   中英

獲取作為基類傳遞的派生C#類的屬性到泛型方法

[英]Get attribute of derived C# class passed as base class to generic method

我試圖確定派生類的屬性值,當它通過基類參數傳遞給方法時。

例如,下面是完整的代碼示例:

class Program
{
    static void Main(string[] args)
    {
        DerivedClass DC = new DerivedClass();
        ProcessMessage(DC);
    }

    private static void ProcessMessage(BaseClass baseClass)
    {
        Console.WriteLine(GetTargetSystemFromAttribute(baseClass));
        Console.ReadLine();
    }

    private static string GetTargetSystemFromAttribute<T>(T msg)
    {
        TargetSystemAttribute TSAttribute = (TargetSystemAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TargetSystemAttribute));

        if (TSAttribute == null)
            throw new Exception(string.Format("Message type {0} has no TargetSystem attribute and/or the TargetSystemType property was not set.", typeof(T).ToString()));

        return TSAttribute.TargetSystemType;
    }
}

public class BaseClass
{}

[TargetSystem(TargetSystemType="OPSYS")]
public class DerivedClass : BaseClass
{}

[AttributeUsage(AttributeTargets.Class)]
public sealed class TargetSystemAttribute : Attribute
{
    public string TargetSystemType { get; set; }
}

所以,在上面的例子中,我原本打算通用的GetTargetSystemFromAttribute方法返回“OPSYS”。

但是,因為DerivedClass實例已作為基類傳遞給ProcessMessage ,所以Attribute.GetAttribute沒有找到任何東西,因為它將DerivedClass視為基類,它沒有我感興趣的屬性或值。

在現實世界中有幾十個派生類,所以我希望避免許多:

if (baseClass is DerivedClass)

...建議作為問題中的答案如何訪問派生類的實例的屬性,該派生類作為基類形式的參數傳遞 (與類似問題有關,但具有屬性)。 我希望因為我對屬性感興趣,有一種更好的方法,特別是因為我有幾十個派生類。

所以,這是問題所在。 有沒有什么辦法可以以低維護的方式獲取派生類的TargetSystem屬性的TargetSystemType值?

你應該改變這一行:

(TargetSystemAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TargetSystemAttribute));

有了這個:

msg.GetType().GetCustomAttributes(typeof(TargetSystemAttribute), true)[0] as TargetSystemAttribute;

PS GetCustomAttributes返回數組並且我選擇了第一個元素,例如,只需要1個屬性,您可能需要更改,但邏輯是相同的。

暫無
暫無

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

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