c# - 如何覆盖 `is` 运算符

标签 c#

我们知道:

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

我发现这是一个不可能的问题:

  1. 如果NotNull<>是类,default(NotNull<>)为空,我什么都不做。
  2. 如果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/

相关文章:

c# - 在公共(public)属性 getter 中使用私有(private)变量

javascript - 无法使用 JSON 将对象列表传递到 View

c# - 如何在 Unity 3D 中包含 SWIG 封装的 C++?

c# - jQuery easySlider 在使用 C# 的 ASP.NET 中不工作

c# - Windows Phone 7 Mango (7.1) - 不重复调用后台任务

c# - 如何在项目MVVM Toolkit中的ViewModel之间共享信息?

c# - DropDownList AppendDataBoundItems(第一项为空且无重复项)

c# - 如何在 MVVM 中工作

c# - Entity Framework 6/SQL Server CE 4 SaveChangesAsync()

c# - 如何动态地将图像添加到 DataGridView(每行的特定列)