【问题标题】:how to use implicit in c# [duplicate]如何在c#中使用隐式[重复]
【发布时间】:2021-06-19 15:10:10
【问题描述】:

我有两个类如下:

class Bear : IPersonality
    {
        ...
    }

class Friend<T> where T : IPersonality
    {
        T friend;

        public Friend(T animal)
        {
            friend = animal;
        }

        ...

        public static implicit operator Friend<T>(Bear v)
        {
            throw new NotImplementedException();
        }
    }

如何使用隐式运算符来创建这样的 Friend 类的实例?

Friend<Bear> bear = new Bear("Pooh", 5);

【问题讨论】:

  • 您可能正在寻找public static implicit operator Friend&lt;T&gt;(T animal) =&gt; animal == null ? null : new Friend&lt;T&gt;(animal);

标签: c# class implicit


【解决方案1】:

如果您对任何动物使用泛型 T,请继续在 implicit 中使用:

 class Friend<T> where T : IPersonality {
   ... 

   public static implicit operator Friend<T>(T animal) => 
     animal == null ? null : new Friend<T>(animal);
 }

如果只有Bear 可以是隐含的朋友(但不是Rabbit),请将代码移至Bear

class Bear : IPersonality {
  ... 

  public static implicit operator Friend<Bear>(Bear bear) =>
    bear == null ? null : new Friend<Bear>(bear);
}

【讨论】:

  • 这是一个奇怪的例子。我喜欢将Nullable<T> 视为标准用例。我以类似的方式对Audit&lt;T&gt; 类型进行了概念化。但是Friend&lt;T&gt; 这个概念似乎不是一个描述符,而是更多的关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2017-07-16
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多