什么是C#的当量与QUOT;对象<物体QUOT;? [英] What is the c# equiv of "object < object"?

查看:109
本文介绍了什么是C#的当量与QUOT;对象<物体QUOT;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些很老的VB.Net code,它是:

I have some very old VB.Net code that is:

 Private Function Min(ByVal A As Object, ByVal B As Object) As Object
            If A Is DBNull.Value Or B Is DBNull.Value Then Return DBNull.Value
            If A < B Then Return A Else Return B
        End Function

没有后顾之忧。编译器吃它....并要求更多。但转换为C#时:

No worries. The compiler eats it.... and asks for more. But when converting to C#:

    private object Min(object A, object B)
    {
        if (object.ReferenceEquals(A, DBNull.Value) | object.ReferenceEquals(B, DBNull.Value))
            return DBNull.Value;
        return A < B ? A : B;
    }

编译器扼流圈它与错误信息:

Compiler chokes on it with error message :

Cannot apply operator '<' with operands of object and object

那么,什么迪丽哟?

So, what the dilly yo?

推荐答案

由于您使用的是VB中的code只适用选项严格关。总的来说,这是非常糟糕的做法。嗯,这是老code照你说的。在现代code(无论是VB或C#),你会使用泛型或/和接口。在code不能被转化为仿制药直接因的DBNull 但这里有一个通用的方法看起来就像在VB中有什么(不包括的DBNull 检查):

The code only works in VB because you are using Option Strict Off. In general this is incredibly bad practice. Well, it’s old code as you say. In modern code (be it VB or C#) you’d use generics or/and interfaces. The code cannot be translated to generics directly due to the DBNull but here’s what a generic approach would look like in VB (without the DBNull check):

Function Min(Of T As IComparable(Of T))(a As T, b as T) As T
    Return If(a.CompareTo(b) < 0, a, b)
End Function

让我们回到你的code,你可以简单地把两个参数 IComparable的确保他们不是在的DBNull ,然后做等价的:

Coming back to your code, you can simply cast the two arguments to IComparable after ensuring that they’re not DBNull, and then do the equivalent:

private object Min(object A, object B)
{
    if (A == DBNull.Value || B == DBNull.Value)
        return DBNull.Value;
    return ((IComparable) A).CompareTo(B) < 0 ? A : B;
}

(为完整起见, C#4具有动态关键字它允许旧的VB code,即推迟方法分派到运行,但我不认为这是最简单的解决方案在这里的道德等价的,我一般preFER有尽可能多的静态检查类型的信息成为可能。)

(For completeness’ sake, C# 4 has the dynamic keyword which allows the moral equivalent of the old VB code, namely deferring method dispatch to runtime. However, I don’t think that’s the most straightforward solution here, and I generally prefer to have as much statically checked type information as possible.)

这篇关于什么是C#的当量与QUOT;对象&LT;物体QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆