我们知道:
int? number = 10;
Console.WriteLine(number is int); // true
但是:
NotNull<string> text = "10"; // NotNull<> is my struct
Console.WriteLine(text is string); // false
我要text is string
返回 true,我该怎么做?
--------------------------------编辑
这是我的 NotNull:
public class NotNull<T> where T : class
{
public T Value { get; }
private NotNull(T value)
{
this.Value = value;
}
public static implicit operator T(NotNull<T> source)
{
return source.Value;
}
public static implicit explicit NotNull<T>(T value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
return new NotNull<T>(value);
}
}
如果一个类声明如下:
public class A
{
public NotNull<string> B { get; set; }
}
我只是希望任何序列化器都可以像这样序列化和反序列化它:
public class A
{
public string B { get; set; }
}
--------------------------------编辑2
我发现这是一个不可能的问题:
- 如果
NotNull<>
是类,default(NotNull<>)
为空,我什么都不做。 - 如果
NotNull<>
是结构,default(NotNull<>).Value
为空。
抱歉这个问题。
最佳答案
在 MSDN 上,您有可重载运算符的列表: Overloadable Operators (C# Programming Guide)
不能重载这些运算符:
=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof
关于c# - 如何覆盖 `is` 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33456416/