2

我有这样声明的类:

internal private abstract class BoxGroup<TS> : IBoxGroup where TS : SavedState

在那个类中,我有这个方法:

protected virtual TS saveState() {
    return new SavedState(Width, Height);
}

我认为这是正确的,但我在 return 声明下看到红线,Resharper 说new SavedState(Width, Height)不能转换为TS. 我不知道为什么。我认为这TS可以是任何扩展的类,SavedState也可以是SavedState它本身。我能做些什么来纠正它?

类保存状态非常简单,如下所示:

private class SavedState {
    internal float Width { get; private set; }
    internal float Height { get; private set; }
    public SavedState(float width, float height) {
        Width = width;
        Height = height;
    }
}
4

2 回答 2

6

这与协方差无关;这是不可能的。

由于TS可以是任何扩展类SavedState,因此您无法将基SavedState实例神奇地转换为任何TS类型。

例如,如果我制作 a BoxGroup<MySpecialSavedState>,您的代码将尝试将基础SavedState对象转换为 a MySpecialSavedState,这是不可能的。

于 2011-01-05T02:10:40.733 回答
2

Here's a small program illustrating one potential way to try and achieve what you want:

using System;

namespace Test
{
    class SaveState
    {
        public int Width { get; set; }
        public int Height { get; set; }
    }

    class SaveStateWithPi : SaveState
    {
        public double Pi
        {
            get { return Math.PI; }
        }
    }

    class Program
    {
        public static T CreateSavedState<T>(int width, int height)
            where T : SaveState, new()
        {
            return new T
                       {
                           Width = width,
                           Height = height
                       };
        }

        static void Main(string[] args)
        {
            SaveState state = CreateSavedState<SaveStateWithPi>(5, 10);

            Console.WriteLine("Width: {0}, Height: {1}", state.Width, state.Height);
        }
    }
}

Basically the idea is to use a new() constraint (thus all of your types derived from SaveState must have a default constructor) and object initializers. Of course this does mean that your SaveState class can't have private setters anymore.

于 2011-01-05T02:18:58.400 回答