【问题标题】:How to determine if a customAttribute from a class is equals to another?如何确定一个类中的 customAttribute 是否等于另一个?
【发布时间】:2012-04-06 05:16:25
【问题描述】:

检查我是否有一个名为 ResponseAttributes 的 customAttribute。我已经声明了一个接口和几个具体的类{ Question 1, Question2, Question3 }

[AttributeUsage(AttributeTargets.Property)]
public class ResponseAttribute : Attribute { }
public interface IQuestion { }

public class Question1 : IQuestion
{
    [Response]
    public string Response { get; set; }
    public Question1() { Response = "2+1"; }
}

public class Question2 : IQuestion
{
    [Response]
    public decimal Response { get; set; }
    public Question2() { Response = 5; }
}

public class Question3 : IQuestion
{
    [Response]
    public string Response { get; set; }
    public Question3() { Response = "2+1"; }
}

现在,我要做的是如何验证包含该属性的类是否等于另一个?

我的意思是:

        List<IQuestion> questions = new List<IQuestion>()
        {
            new Question1(), new Question2()
        };

        Question3 question3 = new Question3();

        foreach (var question in questions)
        {
            // how to verify this condition:
            // if (customAttribute from question3 is equals to customAttribute fromquestion)
            // of course the question3 is equals to 1
        }

你可以,它们是不同的类型,这就是我设置为ResponseAttribute的原因。

【问题讨论】:

  • 为什么需要一个属性?如果您的界面包含一个 Response 属性(即十进制 Response { get;set;} ),您可以通过界面提供的公共属性来比较您的变量
  • 这里的问题是,每个问题都有一个响应属性,但每个问题的数据类型都不同,所以我认为有 customAttribute 很好
  • 使用接口 IQuestion 的好处之一是您可以强制对某些输出使用标准的可比较数据类型。您可能不想更改 Response 的工作方式(保留不同的数据类型),但您可以考虑将接口属性 Answer 添加为字符串,在实现时将 Response 作为字符串输出以进行比较。然后你的 for-each 就变得微不足道了,if questionA.Answer == questionB.Answer...

标签: c# attributes custom-attributes


【解决方案1】:

您可以尝试使用具有 Resposnse 属性(类型对象)的接口 如果你不能,你可以使用一个类级别的属性来告诉你“响应属性”,你可以在该属性上使用反射

例子:

public class ResponseAttribute : Attribute { public string PropertyName { get; set } } [ResponseAttribute ("CustomResponse")} public class Question1 { public string CustomResponse; } via reflection foreach(var question in questions) { var responseAttr = (ResponseAttribute) question.GetType().GetCustomAttributes(typeof(ResponseAttribute)); var questionResponse= question.GetType().GetProperty(responseAttr.PropertyName,question,null); }

【讨论】:

  • 拜托,你能解释一下第二个选项吗?
【解决方案2】:

尝试覆盖equals方法:

    public override bool Equals(object obj)
    {
        if (obj is IQuestion)
            return this.Response == ((IQuestion)obj).Response;
        else
            return base.Equals(obj);
    }

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多