c#中的泛型值对象

本文关键字:对象 泛型 | 更新日期: 2023-09-27 18:18:55

我有一个VO类,它包含几个变量,包括一个变量,可以是不同的类型,并防止转换以后,我想知道我是否可以使该类泛型。

public class InputVO<T>
{
    public bool isEnabled;
    public T value;
}

然后我想创建一个InputVO数组和一个方法来获得一个类型化的InputVO…

public InputVO[] Inputs { get; private set; }
public InputVO GetInput(InputType type)
{
    return Inputs[(int)type];
}

我如何去定义数组和GetInput方法,使它们与通用的InputVO工作?(InputType type参数是一个枚举。

c#中的泛型值对象

泛型类型参数在编译时是固定的。
无论何时使用InputVO,都需要填充该类型参数。

  public InputVO<T1>[] Inputs { get; private set; }

但是你似乎想要的是不同的InputVO对象为每个数据类型,并能够在运行时按类型检索它们:

// Base class for all InputVOs
public abstract InputVOBase
{
    public bool isEnabled;
}
// InputVO for a specific data-type
public class InputVO<T> : InputVOBase
{
    public T Value;
}

现在您可以使用从Type到InputVOBase的字典。

  // One InputVO per datatype
  public Dictionary<Type, InputVOBase> AllInputs { get; private set; }
  // Return the VO for type T, or null
  public InputVO<T> GetInput<T>()
  {
      InputVOBase vo = AllInputs[typeof(T)];
      return (vo as InputVO<T>);
  }

如果不指定类型,则不能创建泛型类的数组。但是,由于您可以控制基类型,因此您可以使其实现非泛型接口并拥有该接口的集合:

//Empty interface 
public interface IInputVO { }
//Your generic class now implements the interface
public class InputVO<T> : IInputVO
{
    public bool isEnabled { get; set; }
    public T Value { get; set; }
}

现在数组的接口类型是IInputVO:

IInputVO[] inputs = 
{ 
    new InputVO<int>(),
    new InputVO<string>(),
    new InputVO<SomeClass>(),
};

稍微清理了一下溶液。主要是需要在字典中收集值。

void Main()
{
    var a = new InputVO<string> { Value = "test" };
    var b = new InputVO<int> { Value = 5 };
    Inputs.Add(typeof(string), a);
    Inputs.Add(typeof(int), b);
    var x = GetInput<string>();
    Console.WriteLine(x.Value);
    var y = GetInput<int>();
    Console.WriteLine(y.Value);
}
public abstract class InputVOBase
{
    public bool isEnabled;
}
public class InputVO<T> : InputVOBase
{
    public T Value;
}
public Dictionary<Type, InputVOBase> Inputs = new Dictionary<Type, InputVOBase>();
public InputVO<T> GetInput<T>()
{
    return Inputs[typeof(T)] as InputVO<T>;
}

谢谢大家的提示!哎呀,因为没有办法绕过类型转换,我只需要考虑几个类型,所以我认为所有基于泛型的解决方案在我的情况下都有点过头了。所以我只是添加了强制转换getter到我的VO…

public class InputVO
{
    public bool isEnabled;
    public bool isValid;
    public InputType type;
    public object value;
    public int IntValue { get { return (int)value; } }
    public float FloatValue { get { return (float)value; } }
    public bool BoolValue { get { return (bool)value; } }
    public Vector2 Vector2Value { get { return (Vector2) value; } }
    public Vector3 Vector3Value { get { return (Vector3)value; } }
}