C# 为什么没有从 SqlDbType 到 DbType 的隐式转换?
C# Why isn't there an implicit cast from SqlDbType to DbType?
我把它归结为一个简单的例子:
using System;
using System.Data;
class MyProgram
{
void DoStuff(DbType t)
{
}
public MyProgram()
{
DoStuff(SqlDbType.Int);
}
}
class Program
{
public static void Main(string[] args)
{
MyProgram p = new MyProgram();
}
}
为什么我必须这样称呼它?
DoStuff((DbType)SqlDbType.Int);
是否仅仅是因为他们只是两个普查员,并且在幕后将他们联系在一起?
干杯,
亚历克斯
SqlDbType 和 DbType 是两个完全独立的枚举。就编译器而言,它们与 enum Colors
和 enum DayOfTheWeek
一样兼容。
你需要执行强制转换来告诉编译器"I know these are different types, but I want you to treat one as the other anyhow."
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
来源:MSDN(强调我的)
请注意,MSDN 没有记录 SqlDbType 或 DbType 的任何特定基础值,因此即使 SqlDbType.BigInt 和 DbType.BigInt 今天具有相同的基础值,也没有书面保证它将保持这种方式,或者在每个 .NET 实现中都是这种方式。
不过MSDN确实做出以下保证
When setting command parameters, the SqlDbType and DbType are linked. Therefore, setting the DbType changes the SqlDbType to a supporting SqlDbType.
处理代码的最佳方式是
DoStuff(DbType.Int);
我把它归结为一个简单的例子:
using System;
using System.Data;
class MyProgram
{
void DoStuff(DbType t)
{
}
public MyProgram()
{
DoStuff(SqlDbType.Int);
}
}
class Program
{
public static void Main(string[] args)
{
MyProgram p = new MyProgram();
}
}
为什么我必须这样称呼它?
DoStuff((DbType)SqlDbType.Int);
是否仅仅是因为他们只是两个普查员,并且在幕后将他们联系在一起?
干杯, 亚历克斯
SqlDbType 和 DbType 是两个完全独立的枚举。就编译器而言,它们与 enum Colors
和 enum DayOfTheWeek
一样兼容。
你需要执行强制转换来告诉编译器"I know these are different types, but I want you to treat one as the other anyhow."
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
来源:MSDN(强调我的)
请注意,MSDN 没有记录 SqlDbType 或 DbType 的任何特定基础值,因此即使 SqlDbType.BigInt 和 DbType.BigInt 今天具有相同的基础值,也没有书面保证它将保持这种方式,或者在每个 .NET 实现中都是这种方式。
不过MSDN确实做出以下保证
When setting command parameters, the SqlDbType and DbType are linked. Therefore, setting the DbType changes the SqlDbType to a supporting SqlDbType.
处理代码的最佳方式是
DoStuff(DbType.Int);