0

检查我是否有一个名为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.

4

2 回答 2

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

于 2012-04-06T07:28:14.263 回答
0

尝试覆盖equals方法:

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

希望这可以帮助

于 2012-04-06T06:16:35.997 回答