是否可以重写 typeof() ?

-2 c# datetime struct types

我有一个自定义结构,内部有本机类型,我想让它表现得像本机类型

这是结构:

private struct test
{
    private DateTime Value;

    public test(DateTime value)
    {
       Value = value;
    }           
}
Run Code Online (Sandbox Code Playgroud)

我希望这是真的:

typeof(test) == typeof(DateTime)
Run Code Online (Sandbox Code Playgroud)

Oli*_*bes 5

typeof不是一个真正的方法,而是一个运算符关键字,它将受到 C# 编译器的特殊处理。您不能覆盖或超载它。

\n

您可以使用隐式转换来代替:

\n
private struct Test\n{\n    private DateTime Value;\n\n    public Test(DateTime value)\n    {\n        Value = value;\n    }\n\n    public static implicit operator Test(DateTime date) => new Test(date);\n    public static implicit operator DateTime(Test test) => test.Value;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

通过隐式转换,您可以编写如下代码:

\n
Test test = DateTime.Now;\nDateTime date = test;\n
Run Code Online (Sandbox Code Playgroud)\n

请小心使用这些 \xe2\x80\x9cmagic\xe2\x80\x9d 转换,否则您的代码可能会变得难以理解。

\n

您还可以将implicit关键字替换为explicit然后编写:

\n
Test test = (Test)DateTime.Now;\nDateTime date = (DateTime)test;\n
Run Code Online (Sandbox Code Playgroud)\n

这更好地体现了程序员的意图。

\n
\n

如果您想要测试类型,您还可以将这些静态方法添加到结构中:

\n
public static bool IsTest(Type t) => t == typeof(Test) || t == typeof(DateTime);\npublic static bool IsTest<T>() => typeof(T) == typeof(Test) || typeof(T) == typeof(DateTime);\npublic static bool IsTest<T>(T _) => typeof(T) == typeof(Test) || typeof(T) == typeof(DateTime);\n
Run Code Online (Sandbox Code Playgroud)\n

他们将允许您执行这些测试:

\n
private void TestMethod<T>()\n{\n    Test test = DateTime.Now;\n    DateTime date = test;\n\n    bool b1 = Test.IsTest(date);\n    bool b2 = Test.IsTest(test);\n    bool b3 = Test.IsTest<T>();\n    bool b4 = Test.IsTest(typeof(DateTime));\n    bool b5 = Test.IsTest(typeof(Test));\n}\n
Run Code Online (Sandbox Code Playgroud)\n

也可以用不同的方式定义价值平等,如链接文章中所述。

\n