在c#中继承泛型

时间:2015-03-10 23:47:55

标签: c# .net generics inheritance decorator

我继承了一个大型代码库,并且我正在尝试在框架中实现一些新功能。基本上,为了以“正确”的方式做到这一点,我将不得不修改框架的整个结构。因为我不是那个设计框架的人,也不是一个心灵读者,这样做可能不会发生(虽然我真的很想从头开始重新设计它)。

所以为了做我想做的事,我正在尝试实现一种装饰模式。 This answer from maliger表明我在下面所做的事情是完全有效的。然而,单声道似乎不喜欢它;它抱怨我宣布T

时无法导出HappyDecorator

请原谅过于简单化的例子,但它得到了重点。

public class HappyObject
{
    public virtual void print()
    {
        Console.WriteLine ("I'm happy");
    }
}

public class VeryHappyObject : HappyObject
{
    public override void print()
    {
        Console.WriteLine ("I'm very happy");
    }

    public void LeapForJoy()
    {
        Console.WriteLine("Leaping For Joy!");
    }
}

public class SuperHappyObject : VeryHappyObject
{    
    public override void print()
    {
        Console.WriteLine ("I'm super happy!");
    }

    public void DieOfLaughter()
    {
        Console.WriteLine("Me Dead!");
    }
}

public class HappyDecorator<T> : T where T : HappyObject
{
    public string SpecialFactor { get; set; }

    public void printMe()
    {
        Console.WriteLine (SpecialFactor);
        print();
    }
}
class MainClass
{
    public static void Main (string[] args)
    {
        HappyDecorator<HappyObject> obj = new HappyDecorator<HappyObject> ();
        obj.SpecialFactor = Console.ReadLine();
        obj.printMe();
    }
}

2 个答案:

答案 0 :(得分:3)

您正在将HappyDecorator键入T,但在该类中没有使用T的实例。

public class HappyDecorator<T> where T : HappyObject
{
    private readonly T _instance;

    public HappyDecorator(T instance)
    {
        _instance = instance;
    }

    public string SpecialFactor { get; set; }

    public void printMe()
    {
        Console.WriteLine(SpecialFactor);
        _instance.print();
    }
}

另一种选择是使用泛型方法而不是泛型类来构造它。然而,它并不是真正的装饰者:

public class HappyDecorator
{
    public string SpecialFactor { get; set; }

    public void printMe<T>(T instance) where T : HappyObject
    {
        Console.WriteLine(SpecialFactor);
        instance.print();
    }
}

并致电:

        HappyDecorator obj = new HappyDecorator();
        obj.SpecialFactor = Console.ReadLine();
        obj.printMe(new HappyObject()); 

答案 1 :(得分:0)

我认为这就是你要做的事情:

    public interface IhappyObject
    {
        void Print();
    }

    public class HappyObject : IhappyObject
    {
        private IhappyObject obj;

        public HappyObject(IhappyObject obj)
        {
            this.obj = obj;
        }

        public void Print()
        {
            obj.Print();
        }
    }

    public class VeryHappyObject : IhappyObject
    {
        public void Print()
        {
            Console.WriteLine("I'm very happy");
        }
    }

    public class SuperHappyObject : IhappyObject
    {
        public void Print()
        {
            Console.WriteLine("I'm super happy!");
        }
    }

    static void Main(string[] args)
    {
        HappyObject obj = new HappyObject(new SuperHappyObject());
        obj.Print();
    }