2012-04-06 39 views
0

檢查我有一個名爲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的原因。

+1

爲什麼你需要一個屬性呢?如果你的界面包含一個Response屬性(即十進制響應{get; set;}),你可以通過界面提供的公共屬性來比較你的變量 – kristian 2012-04-06 05:27:37

+0

這裏的問題是,每個問題都有一個響應屬性,但每一個都是不同的數據類型,所以我認爲使用customAttribute是很好的 – 2012-04-06 14:47:22

+0

使用接口IQuestion的好處之一是可以對某些輸出強制使用標準的可比數據類型。您可能不希望更改Response的工作方式(保留不同的數據類型),但可以考慮將接口屬性'Answer'添加爲一個字符串,該字符串在執行時將輸出Response作爲字符串進行比較。那麼你的for-each變得微不足道,'如果questionA.Answer == questionB.Answer ...' – EtherDragon 2013-10-17 22:00:15

回答

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); 
} 
 
+0

請你能解釋更多關於第二個選項嗎? – 2012-04-06 14:49:31

+0

編輯過的帖子..希望它可以幫助你 – 2012-04-16 10:17:09

0

嘗試重寫equals方法:

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

希望這有助於

相關問題