4

可以按如下方式创建 XNamespace 对象:

XNamespace ns="http://www.xyz.com";

此处字符串“ http://www.xyz.com ”被解释为该类的属性值(NamespaceName)。我想知道我是否可以创建这样一个可以像这样实例化的自定义类。语法实际上看起来很酷。

4

2 回答 2

5
class MyClass
{
    public string Value {get; private set;}
    public MyClass(string s)
    {
        this.Value = s;
    }
    public static implicit operator MyClass(string s)
    {
        return new MyClass(s);
    }
}

现在你可以:

MyClass myClass = "my string";
Console.WriteLine(myClass.Value); //prints "my string"

请注意,XNamespace 还支持加法运算符,它接受字符串作为右参数。如果您正在处理字符串,这是一个非常好的 API 决策。要实现这一点,您也可以重载加法运算符:

//XNamespace returns XName (an instance of another type)
//but you can change it as you would like
public static MyClass operator +(MyClass val, string name) 
{
    return new MyClass(val.Value + name);
}
于 2013-06-19T08:25:53.853 回答
3

You just need to add an implicit conversion operator from string:

public class Foo
{
    private readonly string value;

    public Foo(string value)
    {
        this.value = value;
    }

    public static implicit operator Foo(string value)
    {
        return new Foo(value);
    }
}

I'd use this with caution though - it makes it less immediately obvious what's going on when reading the code.

(LINQ to XML does all kinds of things which are "a bit dubious" in terms of API design... but manages to get away with it because it all fits together so neatly.)

于 2013-06-19T08:25:15.803 回答