简体   繁体   English

C#为什么没有从SqlDbType隐式转换为DbType?

[英]C# Why isn't there an implicit cast from SqlDbType to DbType?

I have boil it down to a simple example: 我将其简化为一个简单的示例:

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();
    }
}

Why do I have to call it this way? 为什么我必须这样称呼它?

DoStuff((DbType)SqlDbType.Int);

Is it simply because they are just two enumerators and there's something behind the scenes linking them together? 仅仅是因为它们只是两个枚举数,并且幕后有一些东西将它们链接在一起吗?

cheers, Alex 干杯,亚历克斯

SqlDbType and DbType are two entirely separate enumerations. SqlDbType和DbType是两个完全独立的枚举。 They are just as compatible as enum Colors and enum DayOfTheWeek would be, as far as the compiler can tell. 就编译器所知,它们与enum Colorsenum DayOfTheWeek兼容。

You need to perform the cast to tell the compiler "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. enum关键字用于声明枚举,这是一种独特的类型 ,由一组称为枚举器列表的命名常量组成。

Source: MSDN (emphasis mine) 资料来源: MSDN (重点是我的)

Note that MSDN does not document any specific underlying values for SqlDbType or DbType, so even if SqlDbType.BigInt and DbType.BigInt have the same underlying value today, there is not a documented guarantee that it will stay that way, or that it is that way on every .NET implementation. 请注意,MSDN并未记录SqlDbType或DbType的任何特定基础值,因此,即使SqlDbType.BigInt和DbType.BigInt今天具有相同的基础值,也无法保证它会保持这种状态,也没有记录在案的保证。 .NET实现中的所有方法。

However MSDN does make the following guarantee 但是MSDN确实提供以下保证

When setting command parameters, the SqlDbType and DbType are linked. 设置命令参数时,将链接SqlDbType和DbType。 Therefore, setting the DbType changes the SqlDbType to a supporting SqlDbType. 因此,设置DbType会将SqlDbType更改为支持的SqlDbType。

The best way to approach your code would be 处理代码的最佳方法是

DoStuff(DbType.Int);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM