我有一个自定义结构,内部有本机类型,我想让它表现得像本机类型
这是结构:
private struct test
{
private DateTime Value;
public test(DateTime value)
{
Value = value;
}
}
我希望这是真的:
typeof(test) == typeof(DateTime)
typeof
不是一个真正的方法,而是一个运算符关键字,它将受到 C# 编译器的特殊处理。您不能覆盖或超载它。
您可以使用隐式转换来代替:
private struct Test
{
private DateTime Value;
public Test(DateTime value)
{
Value = value;
}
public static implicit operator Test(DateTime date) => new Test(date);
public static implicit operator DateTime(Test test) => test.Value;
}
通过隐式转换,您可以编写如下代码:
Test test = DateTime.Now;
DateTime date = test;
请小心使用这些“神奇”转换,否则您的代码可能会变得难以理解。
您还可以将
implicit
关键字替换为 explicit
,然后编写:
Test test = (Test)DateTime.Now;
DateTime date = (DateTime)test;
这更能体现程序员的意图。
如果您想要测试类型,您还可以将这些静态方法添加到结构中:
public static bool IsTest(Type t) => t == typeof(Test) || t == typeof(DateTime);
public static bool IsTest<T>() => typeof(T) == typeof(Test) || typeof(T) == typeof(DateTime);
public static bool IsTest<T>(T _) => typeof(T) == typeof(Test) || typeof(T) == typeof(DateTime);
他们将允许您执行这些测试:
private void TestMethod<T>()
{
Test test = DateTime.Now;
DateTime date = test;
bool b1 = Test.IsTest(date);
bool b2 = Test.IsTest(test);
bool b3 = Test.IsTest<T>();
bool b4 = Test.IsTest(typeof(DateTime));
bool b5 = Test.IsTest(typeof(Test));
}