我有以下属性:
class HandlerAttribute : System.Attribute
{
public string MainName { get; private set; }
public string SubName { get; private set; }
public HandlerAttribute(string pValue, bool pIsMain) {
if (pIsMain) MainName = pValue;
else SubName = pValue;
}
}
这就是我使用属性的方式
[Handler("SomeMainName", true)]
class Class1 {
[Handler("SomeSubName", false)]
void HandleThis() {
Console.WriteLine("Hi");
}
}
我想要实现的是我将MainName值从父类属性导入到类中定义的方法中。
我希望有人可以帮助我:)
提前致谢
答案 0 :(得分:0)
我建议为此编写一个辅助方法,基本上默认情况下是不可能的,因为你无法访问属性的目标。
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class HandlerAttribute : Attribute
{
public string MainName { get; private set; }
public string SubName { get; private set; }
public HandlerAttribute(string pValue, bool pIsMain) {
if (pIsMain) MainName = pValue;
else SubName = pValue;
}
public HandlerAttributeData GetData(MemberInfo info)
{
if (info is Type)
{
return new HandlerAttributeData(MainName, null);
}
HandlerAttribute attribute = (HandlerAttribute)info.DeclaringType.GetCustomAttributes(typeof(HandlerAttribute), true)[0];
return new HandlerAttributeData(attribute.MainName, SubName);
}
}
class HandlerAttributeData
{
public string MainName { get; private set; }
public string SubName { get; private set; }
public HandlerAttributeData(String mainName, String subName)
{
MainName = mainName;
SubName = subName;
}
}
HandlerAttribute att = (HandlerAttribute)typeof(App).GetCustomAttributes(typeof(HandlerAttribute), true)[0];
HandlerAttributeData data = att.GetData(typeof(App));
您可以将它与任何成员一起使用,如果您编写扩展方法,则可以使其更短。
答案 1 :(得分:0)
更新: 您也可以使用此扩展方法。
public static class AttributeExtensions
{
public static string GetMainName(this Class1 class1)
{
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(class1.GetType()); // reflection
foreach (System.Attribute attr in attrs)
{
if (attr is HandlerAttribute)
{
string mainName = (attr as HandlerAttribute).MainName;
return mainName;
}
}
throw new Exception("No MainName Attribute");
}
}
现在,在对扩展方法进行编码之后,您可以在任何Class1类型对象上使用它;
Class1 c1 = new Class1();
string a =c1.GetMainName();
或者您可以直接使用它。
public class HandlerAttribute : System.Attribute
{
public string MainName { get; private set; }
public string SubName { get; private set; }
public HandlerAttribute(string pValue, bool pIsMain)
{
if (pIsMain) MainName = pValue;
else SubName = pValue;
}
}
[Handler("SomeMainName", true)]
class Class1
{
[Handler("SomeSubName", false)]
public void HandleThis()
{
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(this.GetType()); // reflection
foreach (System.Attribute attr in attrs)
{
if (attr is HandlerAttribute)
{
string mainName = (attr as HandlerAttribute).MainName;
}
}
}
}