檢查我有一個名爲ResponseAttributes
的customAttribute。我已經宣佈的接口和一些具體的類{ Question 1, Question2, Question3 }
如何確定一個類的customAttribute是否與另一個類相等?
[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屬性(即十進制響應{get; set;}),你可以通過界面提供的公共屬性來比較你的變量 – kristian 2012-04-06 05:27:37
這裏的問題是,每個問題都有一個響應屬性,但每一個都是不同的數據類型,所以我認爲使用customAttribute是很好的 – 2012-04-06 14:47:22
使用接口IQuestion的好處之一是可以對某些輸出強制使用標準的可比數據類型。您可能不希望更改Response的工作方式(保留不同的數據類型),但可以考慮將接口屬性'Answer'添加爲一個字符串,該字符串在執行時將輸出Response作爲字符串進行比較。那麼你的for-each變得微不足道,'如果questionA.Answer == questionB.Answer ...' – EtherDragon 2013-10-17 22:00:15