开发者

overloading/implicit operator for 'as'

class Person
{
   string Name;
   int Age;
}

I want to be able to cast a string to Person implicitly like following

var mrFoo = "Foo" as Person;

I know I can do the following by defining implicit casting

Person mrFoo = "Foo";

But I'm specific to use "as"开发者_JAVA百科 operator


No, you can't do that. The "as" operator never uses user-defined conversions - only reference conversions and unboxing conversions. Basically, the reference in question already has to be the right type.

Personally I would strongly advise you to stay away from conversion operators (especially implicit ones) for the vast majority of cases. Usually having a conversion method is clearer, e.g. Person.FromString(...).


Have you considered using a parameterized constructor?

var mrFoo = new Person("Foo");


No need to use the as operator, since you can do this with the implicit operator: http://msdn.microsoft.com/en-us/library/z5z9kes2(v=vs.71).aspx

Something along these lines should work:

public static implicit operator Person(string s)
{
  Person p = new Person() {Name = s};
  return p;
}

Now you can simply do:

Person p = "John Doe";
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜