Skip to main content
 首页 » 编程设计

c#之如何使用未知类型的 AS 关键字

2024年02月23日19langtianya

我正在尝试使用未知类型的 AS 关键字。这是我的代码:

public GetData(Type MyType, string CSVPath) 
{ 
    var engine = new FileHelperEngine(MyType); 
 
    try 
    { 
        _Data = engine.ReadFile(CSVPath) as MyType;  //error here 
    } 
    catch(Exception ex) 
    { 
        Console.WriteLine("Error occured: " + ex.Message); 
    } 
} 

如您在这段代码中所见,我收到一个错误,MyType 是。有没有更好的方法来做到这一点

请您参考如下方法:

使用泛型方法而不是将 Type 作为参数传递:

public void GetData<T>(string CSVPath) 
{ 
    var engine = new FileHelperEngine(typeof(T)); 
    _Data = engine.ReadFile(CSVPath) as T; 
    if (_Data != null) 
    { 
        //correct type, do the rest of your stuff here 
    } 
}