获取作为基类传递的派生C#类的属性到泛型方法

Gar*_*eth 6 c# generics polymorphism

我试图确定派生类的属性值,当它通过基类参数传递给方法时.

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

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; }
}
Run Code Online (Sandbox Code Playgroud)

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

但是,因为DerivedClass实例已作为基类传递给ProcessMessage,所以Attribute.GetAttribute没有找到任何东西,因为它将DerivedClass视为基类,它没有我感兴趣的属性或值.

在现实世界中有几十个派生类,所以我希望避免许多:

if (baseClass is DerivedClass)
Run Code Online (Sandbox Code Playgroud)

...建议作为问题的答案如何访问派生类的实例的属性,该派生类以基类的形式作为参数传递(与类似问题有关,但与属性有关).我希望因为我对属性感兴趣,有一种更好的方法,特别是因为我有几十个派生类.

所以,这是问题所在.有没有什么办法可以以低维护的方式获取派生类的TargetSystem属性的TargetSystemType值?

Lev*_*Lev 6

你应该改变这一行:

(TargetSystemAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TargetSystemAttribute));
Run Code Online (Sandbox Code Playgroud)

有了这个:

msg.GetType().GetCustomAttributes(typeof(TargetSystemAttribute), true)[0] as TargetSystemAttribute;
Run Code Online (Sandbox Code Playgroud)

PS GetCustomAttributes返回数组并且我选择了第一个元素,例如,只需要1个属性,您可能需要更改,但逻辑是相同的.

  • 是的:)这是因为TypeOf(T)返回引用变量的类型,而是需要实际对象的类型,即 - msg.GetType(). (2认同)