【问题标题】:C# Generic Casting with Linq使用 Linq 进行 C# 泛型转换
【发布时间】:2011-03-12 17:17:03
【问题描述】:

我有一个与 linq 类接口并使用 System.Data.Linq.Binary 数据类型的类。我正在尝试编写一个简单的类,该类采用通用排列,表示存储为二进制的数据类型:

// .Value is a System.Data.Linq.Binary DataType
public class DataType<T> where T : class
{
     public T Value
     {
        get
        {
            return from d in Database
                   where d.Value = [Some Argument Passed]
                   select d.Value as T;
        }
     }
}

public class StringClass : DataType<string>
{
}

public class ByteClass : DataType<byte[]>
{
}

StringClass.Value 是否会正确转换并从数据库中返回 string

ByteClass.Value 是否会正确转换并从数据库中返回 byte[]

我的主要问题基本上解决了如何使用 System.Data.Linq.Binary。

编辑:如何将 System.Data.Linq.Binary 转换为 T 其中 T 可以是任何东西。我的代码实际上不起作用,因为我无法使用 as 将 Binary 转换为 T。

【问题讨论】:

    标签: c# linq linq-to-sql generics


    【解决方案1】:

    基本上你在做

    System.Data.Linq.Binary b1;
    
    string str = b as string;
    

    System.Data.Linq.Binary b2
    
    byte[] bArray = b2 as byte[];
    

    str 和 bArray 都将为空;

    你需要类似的东西

    public class DataType<T> where T : class
    {
        public T Value
        {
            get
            {
               // call ConvertFromBytes with linqBinary.ToArray()
               // not sure about the following; you might have to tweak it.
                return ConvertFromBytes((from d in Database
                       where d.Value = [Some Argument Passed]
                       select d.Value).
                First().ToArray());
            }
        }
    
        protected virtual T ConvertFromBytes(byte[] getBytes)
        {
            throw new NotImplementedException();
        }
    }
    
    public class StringClass : DataType<string>
    {
        protected override string ConvertFromBytes(byte[] getBytes)
        {
            return Encoding.UTF8.GetString(getBytes);
        }    
    }
    
    public class ByteClass : DataType<byte[]>
    {
        protected override byte[] ConvertFromBytes(byte[] getBytes)
        {
            return getBytes;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多