如何在枚举中添加.Equals()扩展名?

Spa*_*ose 2 c#

我目前有以下代码:

public enum FieldType
{
    Int,
    Year,
    String,
    DateTime
}
public enum DataType
{
    Int,
    String,
    DateTime
}
Run Code Online (Sandbox Code Playgroud)

我想为每个方法都有一个扩展方法,这样我就可以这样做:

FieldType fType = FieldType.Year;
DataType dType = DataType.Int;

fType.Equals(dType); //If fType is an Int/Year, and dType is an Int it should return true
dType.Equals(fType); //If dType is an Int, and fType is an Int/Year it should be true
Run Code Online (Sandbox Code Playgroud)

有没有办法创建一个.Equals扩展,这样就可以了?

Jon*_*eet 8

那你可以写:

public static class Extensions
{
    public static bool Equals(this FieldType field, DataType data)
    {
        return data.Equals(field);
    }

    public static bool Equals(this DataType data, FieldType field)
    {
        // Insert logic here
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定我会不会 ...因为你object.Equals以不一致的方式超载.所以如果有人写道:

object field = FieldType.Int;
Console.WriteLine(field.Equals(DataType.Int));
Run Code Online (Sandbox Code Playgroud)

将打印False,因为它将使用object.Equals而不是扩展方法.