【问题标题】:Recursive generic class declaration without using interface不使用接口的递归泛型类声明
【发布时间】:2015-11-04 18:11:08
【问题描述】:

我有以下代码作为搜索的对象模型,用户在客户端执行此操作,效果很好:

public class DemographicAttribute
{
    public string DemographicAttributeValue { get; set; }
}

public class AudienceOperators<T>: IAudienceOperators
{
    public string DemographicAttributeType { get; set; }
    public List<T> Operand { get; set; }
    public string Operator { get; set; }
    //List<U> Entity2 { get; set; }

    public AudienceOperators(List<T> operand, string _operator = null, string demographicAttributeType = "")
    {
        Operand = operand;
        Operator = _operator;
        DemographicAttributeType = demographicAttributeType;
    }
}


public interface IAudienceOperators {}

用法如下:

DemographicAttribute atr1 = new DemographicAttribute();
atr1.DemographicAttributeType = "Occupation";
atr1.DemographicAttributeValue = "White collar";

DemographicAttribute atr2 = new DemographicAttribute();
atr2.DemographicAttributeType = "Occupation";
atr2.DemographicAttributeValue = "Blue";

DemographicAttribute atr3 = new DemographicAttribute();
atr3.DemographicAttributeType = "Age";
atr3.DemographicAttributeValue = "10 - 14";

DemographicAttribute atr4 = new DemographicAttribute();
atr4.DemographicAttributeType = "Age";
atr4.DemographicAttributeValue = "15 - 25";

AudienceOperators<String> op1 = new AudienceOperators<String>(new List<String> { atr1.DemographicAttributeValue, atr2.DemographicAttributeValue }, "OR", atr1.DemographicAttributeType);
AudienceOperators<String> op2 = new AudienceOperators<String>(new List<String> { atr3.DemographicAttributeValue, atr4.DemographicAttributeValue }, "OR", atr3.DemographicAttributeType);
AudienceOperators<IAudienceOperators> op3 = new AudienceOperators<IAudienceOperators>(new List<IAudienceOperators> { op1, op2 }, "AND");

为了能够像 T 那样创建泛型类的实例,我需要创建空白接口。但我认为,这不是最好的代码实践。有没有其他办法?

【问题讨论】:

  • 我需要创建空白界面是什么意思?
  • 他想要Foo&lt;Foo&lt;&gt;&gt;,这是不可能的。
  • @PatrickHofman:我认为 OP 意味着空接口。
  • 这看起来有点像装饰器模式。我建议检查一下,也许它对你有用。
  • 感谢您的帮助,Foo> 完成了这项工作。

标签: c# generics recursion


【解决方案1】:

也许,使用对象?

AudienceOperators<object> op3 = new AudienceOperators<object>(new List<object> { op1, op2 }, "AND");

而且您不必声明 IAudienceOperators。

【讨论】:

    【解决方案2】:

    您不需要做任何特别的事情来允许“递归”通用实例。

    public class Recursively<T> {
        public T Instance { get; set; }
    }
    
    ...
    
    var recursively = new Recursively<Recursively<Recursively<string>>>();
    Console.WriteLine(recursively.Instance.GetType().ToString());
    Console.Writeline(recursively.Instance.Instance.GetType().ToString());
    Console.Writeline(recursively.Instance.Instance.Instance.GetType().ToString());
    

    【讨论】:

      猜你喜欢
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多