繁体   English   中英

从泛型类转换为类型

[英]Cast to a type from a generic class

我有一个通用的类,看起来像这样:

public interface IStationProperty
   {
      int Id { get; set; }
      string Desc { get; set; }
      object Value { get; }
      Type ValueType { get; }
   }

   [Serializable]
   public class StationProp<T> : IStationProperty
   {
      public StationProp()
      {
      }

      public StationProp(int id, T val, string desc = "")
      {
         Id = id;
         Desc = desc;
         Value = val;
      }

      public int Id { get; set; }
      public string Desc { get; set; }
      public T Value { get; set; }

      object IStationProperty.Value
      {
         get { return Value; }
      }

      public Type ValueType
      {
         get { return typeof(T); }
      }

获取类型的属性是:

public Type ValueType
      {
         get { return typeof(T); }
      }

因此,在我的代码中,我有一个循环从数据库中提取值(作为字符串),在这里我想进行类型转换(在左侧),以便可以进行可靠的值比较。

我想要这样的东西:

var correctlyTypedVariable = (prop.ValueType) prop.Value; 

我知道这种事情必须可行。

你已经有了

public T Value { get; set; }

它返回输入的值。 如果在以下代码上,则prop对象的类型为IStationProperty

var correctlyTypedVariable = (prop.ValueType) prop.Value; 

那么也许您的问题出在接口上:您最好使用通用的接口:

public interface IStationProperty
{
  int Id { get; set; }
  string Desc { get; set; } 
  Type ValueType { get; }
}

public interface IStationProperty<T> : IStationProperty
{ 
   T Value { get; } 
}

使用IComparable:

public interface IStationProperty : IComparable<IStationProperty>
{
    int Id { get; set; }
    string Desc { get; set; }
    object Value { get; }
    Type ValueType { get; }
}

[Serializable]
public class StationProp<T> : IStationProperty where T : IComparable
{
    public StationProp()
    {
    }

    public StationProp(int id, T val, string desc = "")
    {
        Id = id;
        Desc = desc;
        Value = val;
    }

    public int Id { get; set; }
    public string Desc { get; set; }
    public T Value { get; set; }

    object IStationProperty.Value
    {
        get { return Value; }
    }

    public Type ValueType
    {
        get { return typeof(T); }
    }

    public int CompareTo(IStationProperty other)
    {
        if (other.ValueType == typeof(string))
        {
            return Value.CompareTo((string)other.Value);
        }
        else if (other.ValueType == typeof(int))
        {
            return Value.CompareTo((int)other.Value);
        }
        else if (other.ValueType == typeof(double))
        {
            return Value.CompareTo((double)other.Value);
        }
        throw new NotSupportedException();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM