获取派生的 C# 类的属性,作为基类传递给泛型方法
本文关键字:基类 泛型方法 派生 属性 获取 | 更新日期: 2023-09-27 18:32:11
我正在尝试确定派生类上的属性值,当它通过基类参数传递到方法中时。
例如,下面的完整代码示例:
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)
。建议作为问题"如何访问派生类实例的属性"中的答案,该实例以基类的形式作为参数传递(与类似问题有关,但具有属性)。我希望因为我对属性感兴趣,所以有一种更好的方法,特别是因为我有几十个派生类。
所以,问题来了。有什么方法可以以低维护的方式获取派生类上目标系统属性的 TargetSystemType 值?
您应该更改此行:
(TargetSystemAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(TargetSystemAttribute));
有了这个:
msg.GetType().GetCustomAttributes(typeof(TargetSystemAttribute), true)[0] as TargetSystemAttribute;
附言 GetCustomAttributes 返回数组,我选择了第一个元素,例如,其中只有 1 个属性,您可能需要更改,但逻辑是相同的。