簡體   English   中英

C#類型轉換,泛型中應該如何實現?

[英]C# Type Casting, How Should be Implemented In Generics?

我想將一些文本文件轉換為我的代碼實體。

這些文件包含實體信息,例如,一個包含客戶信息,一個包含訂單信息,另一個包含供應商信息。

我已經將字符串到實體類型轉換為實體類。

由於讀取文本文件並將每一行轉換為字符串是不同實體的常見任務,因此我使用了一個通用類來讀取文本文件並將其轉換為實體。

public class TextToEntity<TEntity> 
{
    private string _txtfile { get; set; }
    public TextToEntity(string TextFile)
    {
        _txtfile = TextFile;
    }

    public List<TEntity> ReadText()
    {
        return File.ReadAllLines(_txtfile).Select(c =>
        {
            return (TEntity)c;
        }).ToList();
    }
} 

return (TEntity)c

導致錯誤

無法將字符串轉換為 TEntity

我知道我應該給 TextToEntity 一個約束,比如:

public class TextToEntity<TEntity> where TEntity:Customer,Supplier,Order

但這不是真正的語法,真正的形式是什么?

有人可以幫忙嗎?

我認為你的設計很糟糕......無論如何這里有一個簡單的“黑客”:

public List<TEntity> ReadText()
{
    return File.ReadAllLines(_txtfile).Select(c =>
    {
        var method = typeof(TEntity).GetMethod("op_Explicit", new[] { typeof(string) });

        return (TEntity) method.Invoke(null, new[] { c });

    }).ToList ();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM