奇怪的重复模板模式,多层继承

本文关键字:模式 继承 | 更新日期: 2023-09-27 18:15:37

在这里完成的工作的基础上,我为枚举定义了一个通用的抽象基类,如下所示:

public abstract class Enumeration<T> : IEquatable<T> where T : Enumeration<T>
{
    private static IEnumerable<T> enumerateAllValues()
    {
        // Obviously use some caching here
        var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
        return fields.Select(f => f.GetValue(null)).OfType<T>();
    }
    internal static IEnumerable<T> AllValues {get { return enumerateAllValues();}}
    protected Enumeration(int value, string displayName)
    {
        if (!typeof(T).IsSealed)
            throw new NotSupportedException($"Value objects must be sealed, {typeof(T).Name} is not.");
        this.Value = value;
        this.DisplayName = displayName;
    }
    protected int Value { get; }
    protected string DisplayName { get; }
    public override string ToString() { return DisplayName; }       
    // IEquatable implementation based solely on this.Value
}

以及用于解析和列出枚举值的静态非泛型帮助类:

public static class Enumeration 
{
    public static IEnumerable<T> GetAllValues<T>() where T : Enumeration<T>
        {
            return Enumeration<T>.AllValues;
        }
    // Other helper methods, e.g. T Parse(int), bool TryParse(int, out T), etc.
}

现在,我从它派生出另一个抽象类来表示具有某些共同点的枚举类:

public abstract class AnimalTrait<T> : Enumeration<AnimalTrait<T>>
{
    protected AnimalTrait(int value, string displayName) : base(value, displayName) { ; }
}

到目前为止一切顺利。作为一个例子,从它派生的具体类可能是DogTrait,或者FishTrait,等等。知道所有动物特征都可以与值配对,并且假设动物特征的值总是一个字符串,然后定义另一个抽象类,如下所示:

public struct AnimalTraitValuePair<TAnimalTrait> where TAnimalTrait : AnimalTrait<TAnimalTrait>
{
    public TAnimalTrait AnimalTrait { get; }
    public string Value { get; } // Analogy breaks down here, but lets assume we know that the values of animal traits are always strings.
    public AnimalTraitValuePair(TAnimalTrait animalTrait, string value)
    {
        this.AnimalTrait = animalTrait;
        this.Value = value;
    }
    public override string ToString()
    {
        return $"[{AnimalTrait}, {Value}]";
    }
}

类似于从KeyValuePair<TAnimalTrait, string> where TAnimalTrait : AnimalTrait<TAnimalTrait>派生,如果它不是一个结构体,我会这样做。

现在,当我去定义Animal类,它包含动物的名字和它的AnimalTrait列表及其相关值,即AnimalTraitValuePair<TAnimal>列表,我遇到了一个问题:

public abstract class Animal<TAnimal, TAnimalTrait> :
    where TAnimal : Animal<TAnimal, TAnimalTrait>
    where TAnimalTrait : AnimalTrait<TAnimalTrait>
{
    private readonly IList<AnimalTraitValuePair<TAnimalTrait>> animalTraitValuePairList;
    // All animals have a name
    public string Name {get;}
    protected Animal(string name, IEnumerable<AnimalTraitValuePair<TAnimalTrait>> animalTraitValuePairs)
    {
        animalTraitValuePairList = animalTraitValuePairs.ToList();
        this.Name = name;
    }
    public string this[TAnimalTrait animalTrait]
    {
        get
        {
            return animalTraitValuePairList.First(atvp => atvp.AnimalTrait == animalTrait).Value;
        }
    }
    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        // !!!! BREAKS HERE !!!!
        foreach (var animalTrait in Enumeration.GetAllValues<AnimalTrait<TAnimalTrait>>()) // This works...
        //foreach (var animalTrait in Enumeration.GetAllValues<TAnimalTrait>()) // ...but this doesn't
        {
            sb.AppendLine($"{this.Name}'s traits:");
            sb.AppendLine($"[{animalTrait}, {animalTrait.Value}]");
        }
        return sb.ToString();
    }
}

我得到这个编译错误:

The type 'TAnimalTrait' cannot be used as type parameter 'T' in the generic type or method 'Enumeration.GetAllValues<T>()'. There is no implicit reference conversion from 'TAnimalTrait' to 'Maxim.Common.Enums.Enumeration<TAnimalTrait>'

为什么我不能直接使用TAnimalTrait ?是不是TAnimalTrait被限制为AnimalTrait<TAnimalTrait>的一个类,我们知道这是一个枚举,因此可以提升两个级别到基础Enumeration<T> ?编译"正确"并提供我想要的行为的程序是否正确?

奇怪的重复模板模式,多层继承

您的代码有许多问题,我不知道我必须更改的所有内容,但这里有一个工作片段:

void Main()
{
    Console.WriteLine(Dog.Fido.ToString());
}
public abstract class Enumeration<T> where T : Enumeration<T>
{
    private static IEnumerable<T> enumerateAllValues()
    {
        // Obviously use some caching here
        var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
        return fields.Select(f => f.GetValue(null)).OfType<T>();
    }
    internal static IEnumerable<T> AllValues { get { return enumerateAllValues();}}
    protected Enumeration(int value, string displayName)
    {
        if (!typeof(T).IsSealed)
            throw new NotSupportedException($"Value objects must be sealed, {typeof(T).Name} is not.");
        this.Value = value;
        this.DisplayName = displayName;
    }
    protected int Value { get; }
    protected string DisplayName { get; }
    public override string ToString() { return DisplayName; }       
        // IEquatable implementation based solely on this.Value
}
public static class Enumeration
{
    public static IEnumerable<T> GetAllValues<T>() where T : Enumeration<T>
    {
        return Enumeration<T>.AllValues;
    }
    // Other helper methods, e.g. T Parse(int), bool TryParse(int, out T), etc.
}
public abstract class AnimalTrait<T> : Enumeration<T>
    where T : AnimalTrait<T>
{
    protected AnimalTrait(int value, string displayName) : base(value, displayName) {; }
}
public struct AnimalTraitValuePair<TAnimalTrait> where TAnimalTrait : AnimalTrait<TAnimalTrait>
{
    public TAnimalTrait AnimalTrait { get; }
    public string Value { get; } // Analogy breaks down here, but lets assume we know that the values of animal traits are always strings.
    public AnimalTraitValuePair(TAnimalTrait animalTrait, string value)
    {
        this.AnimalTrait = animalTrait;
        this.Value = value;
    }
    public override string ToString()
    {
        return $"[{AnimalTrait}, {Value}]";
}
}
public abstract class Animal<TAnimal, TAnimalTrait> : Enumeration<TAnimal>
    where TAnimal : Animal<TAnimal, TAnimalTrait>
    where TAnimalTrait : AnimalTrait<TAnimalTrait>
{
    private readonly IList<AnimalTraitValuePair<TAnimalTrait>> animalTraitValuePairList;
    // All animals have a name
    public string Name { get; }
    protected Animal(int i, string name, IEnumerable<AnimalTraitValuePair<TAnimalTrait>> animalTraitValuePairs)
        : base(i, name)
    {
        animalTraitValuePairList = animalTraitValuePairs.ToList();
        this.Name = name;
    }
    public string this[TAnimalTrait animalTrait]
    {
        get
        {
            return animalTraitValuePairList.First(atvp => atvp.AnimalTrait == animalTrait).Value;
        }
    }
    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"{this.Name}'s traits:");
        foreach (var animalTrait in Enumeration.GetAllValues<TAnimalTrait>())
        {
            sb.AppendLine($"[{animalTrait}, {this[animalTrait]}]");
        }
        return sb.ToString();
    }
}
public sealed class DogTrait : AnimalTrait<DogTrait>
{
    public DogTrait(int i, string name) 
        : base(i, name)
    { }
    public static DogTrait Color = new DogTrait(1, "Color");
    public static DogTrait Size = new DogTrait(2, "Size");
}
public sealed class Dog : Animal<Dog, DogTrait>
{
    public Dog(int i, string name, IEnumerable<AnimalTraitValuePair<DogTrait>> animalTraitValuePairs)
        : base(i, name, animalTraitValuePairs)
    {
    }
    public static Dog Fido = new Dog(1, "Fido", new[] {
        new AnimalTraitValuePair<DogTrait>(DogTrait.Color, "Black"),
        new AnimalTraitValuePair<DogTrait>(DogTrait.Size, "Medium"),
    });
}
输出:


狗的特征:(颜色,黑色)
[Size, Medium]

你对AnimalTraitValuePair有一个约束

public struct AnimalTraitValuePair<TAnimalTrait> 
   where TAnimalTrait : AnimalTrait<TAnimalTrait>

当你使用它时,你传递了一个带有Animal约束的TAnimal

public abstract class Animal<TAnimal, TAnimalTrait> 
    : IEnumerable<AnimalTraitValuePair<TAnimal>>
    where TAnimal : Animal<TAnimal, TAnimalTrait>
    where TAnimalTrait : AnimalTrait<TAnimalTrait>

如果您将其更改为以下内容:

public abstract class Animal<TAnimal, TAnimalTrait> 
:  IEnumerable<AnimalTraitValuePair<TAnimalTrait>>
    where TAnimal : Animal<TAnimal, TAnimalTrait>
    where TAnimalTrait : AnimalTrait<TAnimalTrait>

你会得到一个错误,说明

Enumeration<AnimalTrait<TAnimalTrait>>.Value is inaccessable due to its protection level. 

这是因为你的Animal类没有从Enumeration>

老实说,作为一个ist是IEnumerable的通用实现,如果您想要一个实现相同目标的简单实现,我只需执行以下操作:

public class Animal
{
   private IList<AnimalTrait> _traits;
   public Animal(IList<AnimalTrait> traits)
   {
       _traits = traits;
   }
   public IEnumerable<AnimalTrait> Traits{get{return _traits;}}
}
public class AnimalTrait
{
   public int Value{get;set;}
   public string DisplayName{get;set;}
}