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

获取作为基类传递给泛型方法的派生C#类的属性,c#,generics,polymorphism,C#,Generics,Polymorphism,我试图确定派生类上的属性值,当它通过基类参数传递到方法中时 例如,下面完整的代码示例: class Program { static void Main(string[] args) { DerivedClass DC = new DerivedClass(); ProcessMessage(DC); } private static void ProcessMessage(BaseClass baseClass) {

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

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

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; }
}
…这是问题的答案(与类似问题有关,但具有属性)。我希望,因为我对属性感兴趣,有一种更好的方法来实现它,特别是因为我有几十个派生类


所以,问题来了。是否有任何方法可以以低维护方式在派生类上获取TargetSystem属性的TargetSystemType值

您应该更改此行:

(TargetSystemAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TargetSystemAttribute));
为此:

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

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

Ups,应该用一种简单的方式重写它:在代码中,而不是在typeof(T)中使用msg.GetType():),因此我现在有了:TargetSystemAttribute TsaAttribute=(TargetSystemAttribute)GetCustomAttribute(msg.GetType(),typeof(TargetSystemAttribute));是的,它起作用了。太好了,谢谢。是的:)发生这种情况是因为TypeOf(T)返回引用变量的类型,但您需要实际对象的类型,即-msg.GetType()。
msg.GetType().GetCustomAttributes(typeof(TargetSystemAttribute), true)[0] as TargetSystemAttribute;