List of Generics T using Interface

本秂侑毒 提交于 2020-01-06 04:09:07

问题


Following these two SO questions:

Is it possible to use a list of untyped generics in C#?

and

How am I able to create A List<T> containing an open generic Interface?

  public interface IValue
{
    object Min { get; set; }
    object Max { get; set; }
    object Avg { get; set; }
}

public abstract class Value<T> : IValue
{
     abstract T Min;
     abstract T Max;
     abstract T Avg;
    object IValue.Avg { get { return Avg; } }
    object IValue.Min { get { return Min; } }
    object IValue.Max { get { return Max; } }

    public Value(T min, T max, T avg)
    {
        Min = min;
        Max= max;
        Avg = avg;
    }
}

Somewhere else in code....

Value myValue = new Value<ulong>(x, y, z);
Value myValue = new Value<ushort>(x, y, z);
List<IValue> myList = new List<IValue>();
myList.add(myValue);
//Do stuff like myList[0].Min

I can't get this to work properly. I Imagine it has to do with my interface and how I'm using it. I want to be able to call a constructor and set the values however I need to.

I get errors like "modifier 'abstract' not valid on fields. Try a property instead" and "Cannot create an instance of the abstract class of interface Value" but I also can't do new IValue either.


回答1:


Why do you use abstract at all? If you want to create class instances the class can't be abstract.

public class Value<T>: IValue {
  // Better to name these fields as "min, max, ave" or "m_Min, m_Max, m_Ave"
  T Min;
  T Max;
  T Avg;

  // Do not forget about "set" accessors
  object IValue.Avg {
    get { return Avg; }
    set { Avg = (T) value; }
  }

  object IValue.Min {
    get { return Min; }
    set { Min = (T) value; }
  }

  object IValue.Max {
    get { return Max; }
    set { Max = (T) value; }
  }

  public Value(T min, T max, T avg) {
    Min = min;
    Max = max;
    Avg = avg;
  }
}

...

// "Value<ulong> myValue" instead of "Value myValue "
Value<ulong> myValue = new Value<ulong>(x, y, z);
List<IValue> myList = new List<IValue>();
myList.Add(myValue);



回答2:


  • You can’t create an object of an interface, so you can’t do new IValue().

  • You can’t create an object of an abstract type, so you can’t do new Value<SomeType>() either.

  • In Value<T>, Min, Max and Avg are fields, and fields cannot be abstract. You want to make properties instead:

    public abstract T Min { get; set; }
    public abstract T Max { get; set; }
    public abstract T Avg { get; set; }
    
  • You probably don’t want to use abstract at all. Value<T> looks pretty complete, and given that you expect to be able to create it, there is no reason to have it as an abstract type.



来源:https://stackoverflow.com/questions/22407465/list-of-generics-t-using-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!