如何确定一个类中的自定义属性是否等于另一个类
本文关键字:自定义属性 是否 另一个 一个 何确定 | 更新日期: 2023-09-27 18:30:17
检查我是否有一个名为ResponseAttributes
的自定义属性。我已经声明了一个接口和几个具体的类{ 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
的原因.
您可以尝试使用带有 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);
}
try overriding equals method:
public override bool Equals(object obj)
{
if (obj is IQuestion)
return this.Response == ((IQuestion)obj).Response;
else
return base.Equals(obj);
}
希望这有帮助