开发者

elegant string splitting

I am looking for a nicer way of acc开发者_运维知识库omplishing the following code block which is part of an EmailAddress class/object. To my thinking, the parts array is clunky and I'm wondering if there isn't a one liner using tuples or Linq that would tidy it up a bit.

Also, what would be a better property name than "Alias" for the first part of the email address?

public string Alias { get; private set; }
public string Domain { get; private set; }
private void Split(string emailAddress)
{
    var parts = emailAddress.Split(new[] { '@' });
    Alias = parts[0];
    Domain = parts[1];
}


Well, it's less clunky if you take advantage of the parameter array:

var parts = emailAddress.Split('@');

Or (to avoid creating a new array every time) you could reuse an existing array:

private static readonly char[] EmailSplitter = new char[] {'@'};
...
var parts = emailAddress.Split(EmailSplitter);

Beyond that, I don't see that it's particularly clunky - although if this is all that the EmailAddress class does, I'd do this in the constructor (or a static method) and make the object immutable.

You might want to use "localpart" instead of "alias" - that would be in-keeping with RFC-822.


I would say that is fine.

Another way would be to use a regular expression, but you wouldn't gain much other than being able to validate the format at the same time as splitting it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜