检查我是否有一个名为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
的原因。
答案 0 :(得分: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);
}
答案 1 :(得分:0)
尝试覆盖equals方法:
public override bool Equals(object obj)
{
if (obj is IQuestion)
return this.Response == ((IQuestion)obj).Response;
else
return base.Equals(obj);
}
希望这会有所帮助