我试图确定派生类的属性值,当它通过基类参数传递给方法时.
例如,下面是完整的代码示例:
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)
……在问题How to access the properties of an instance of a derived class which is passed as a parameter in the form of the base class中提出了答案(涉及类似的问题,但涉及属性).我希望因为我对属性感兴趣,有一种更好的方法,特别是因为我有几十个派生类.
所以,这是问题所在.有没有什么办法可以以低维护的方式获取派生类的TargetSystem属性的TargetSystemType值?
解决方法:
你应该改变这一行:
(TargetSystemAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TargetSystemAttribute));
有了这个:
msg.GetType().GetCustomAttributes(typeof(TargetSystemAttribute), true)[0] as TargetSystemAttribute;
附: GetCustomAttributes返回数组,我选择了第一个元素,例如,只需要1个属性,您可能需要更改,但逻辑是相同的.