开发者

Type conversion from string to User defined type

I have a string type to be assigned to owner of type 'U开发者_运维技巧ser'. My method GetFullName returns the name in a 'string' format and i need to assign it to owner of type 'User'

def.Owner = uf.GetFullName(row["assignedto"].ToString());

Any suggestions would be helpful,


So you need something like:

public class User
{
    ...

    public static implicit operator User(string x)
    {
        return new User(x);
    }
}

Personally, I'm not a fan of implicit conversions, however. You say that you "need" to assign it this way... what's wrong with an explicit constructor or static method call? Or perhaps an extension method (ToUser) on string?


@Jon's answer will do what you want, but you may want to look into the repository pattern for managing the creation of domain objects. That'll solve the bigger problem of making sure the code that uses the domain objects doesn't become wrapped around the axle just managing their lifetimes and serialization/deserialization. Let the repository take care of such concerns and focus on your domain logic.


There is a solution with conversion operator, however, I'd personally prefer a static class method like User.FromString(string s) that parses the string and constructs a User instance. This way the code with be more readable and much easier to understand


You can overload the explicit/implicit operators.
Take a look here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜