开发者

Problem with implicit conversion and null

开发者 https://www.devze.com 2022-12-16 01:01 出处:网络
I have this function public static implicit operator MyClass(string v) { return new MyClass(v); } and write var.myclass = null;. This calls the implicit operator and passes null as string, which ca

I have this function

public static implicit operator MyClass(string v) { return new MyClass(v); }

and write var.myclass = null;. This calls the implicit operator and passes null as string, which causes havoc in my code (i use reflection and would not like to add a special case). How can i write myclass = null without causing the implicit operator?

I tried 开发者_运维百科writing

public static implicit operator MyClass(string v) { return  v == null ? null : new MyClass(v); }

But that causes a stackoverflow


I believe that your problem is that both sides of the ternary operator must be of the same or compatible types.

Try writing

if (v == null)
    return null;
else
    return new MyClass(v);

EDIT: I can only reproduce your issue if I make MyClass a struct, in which case your question is impossible; a struct cannot be null.

Please provide more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消