开发者

Cast - string to Custom<string>

I have a custom wrapper object for my properties: MyType<t>. I have private members of these types and public members of type t.

I'm trying to load the object and am getting a cast error:

Unable to cast object of type 'System.String' to type 'Model.MyType`1[System.String]

I have a method for the following:

private t _value;

public static implicit  operator t(MyType<t> obj)
{
    return obj._value;
}

Any help in what I'm missing to make the cast work would be great.

Update:

The member looks like the开发者_运维百科 following:

 MyType<string> PostalCode =  new MyType<string>();

I'm loading the properties with Dapper and the methods that were suggested are not being hit. So when the reflection engine tries to load the objects the implicit cast is not firing.


Your operator is backwards. It supports casting from MyType<t> to t. You want the other way around. Perhaps something like this is what you are looking for.

 private t _value;

 private MyType(t val)
 {
      _value = val;
 }

 public static implicit operator MyType<t>(t obj)
 {
     return new MyType<t>(obj);
 }

Using the constructor is optional, I personally just find that cleaner. You could just use the default constructor and set the field explicitly in your operator as well.


Your implicit cast operator is working in the reverse direction to what the error is complaining about, you need to implement the other implicit operator to go from t to MyType<t>.

You can also do the same with explicit casting (where you do something like string foo = (string)someObject;):

http://msdn.microsoft.com/en-us/library/xhbhezf4(v=vs.71).aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜