如何在c#中使用隐式
how to use implicit in c#
我有两个 class如下:
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 class 的实例?
Friend<Bear> bear = new Bear("Pooh", 5);
如果您对任何动物使用仿制药 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);
}
我有两个 class如下:
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 class 的实例?
Friend<Bear> bear = new Bear("Pooh", 5);
如果您对任何动物使用仿制药 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);
}