簡體   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