【发布时间】: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