Skip to main content
 首页 » 编程设计

c#之如何删除 C# 中的强类型

2024年02月05日11xxx_UU

假设我必须将从数据库中读取的内容转换为对象。我可能有这样的东西:

public class Foo { 
 
    int a; 
    DateTime b; 
    float c; 
 
    public Foo(int a, DateTime b, float c) { 
        this.a = a; 
        this.b = b; 
        this.c = c; 
    } 
 
    internal Foo(DataRow dr) { 
        this.a = (int) dr["a"]; 
        this.b = (DateTime) dr["b"]; 
        this.c = (float) dr["c"]; 
    } 
 
} 

有没有什么你可以做的,也许使用 dynamic 关键字,可以删除类型检查并自动转换?理想情况下,它只适用于 internal 构造函数。

请您参考如下方法:

你是说这样?

public class Foo { 
    dynamic a; 
    dynamic b; 
    dynamic c; 
 
    public Foo(int a, DateTime b, float c) { 
        this.a = a; 
        this.b = b; 
        this.c = c; 
    } 
    internal Foo(DataRow dr) { 
        this.a = dr["a"]; 
        this.b = dr["b"]; 
        this.c = dr["c"]; 
    } 
} 

当然,如果你真的很讨厌转换,你可以这样做,然后编译器不再是你最好的 friend ,以防止你搬起石头砸自己的脚。

如果摆脱丑陋的转换是您的主要关注点,另一种方法是使用 DataRowExtensions.Field<T>方法扩展。

Provides strongly-typed access to each of the column values in the specified row.

使用示例:

public class Foo { 
    int a; 
    DateTime b; 
    float c; 
 
    public Foo(int a, DateTime b, float c) { 
        this.a = a; 
        this.b = b; 
        this.c = c; 
    } 
    internal Foo(DataRow dr) { 
        this.a = dr.Field<int>("a"); 
        this.b = dr.Field<DateTime>("b"); 
        this.c = dr.Field<float>("c"); 
    } 
}