2

当你有一个与类型同名的局部变量时,有没有办法告诉编译器你给出的符号是类型还是变量?例如考虑(并忽略所有类型返回错误):

public class sometype { public static sometype DoSomething() {} }

public string sometype { get { return sometype.DoSomething(); } } //A
public string sometype { get { return sometype.Trim(); } } //B
public sometype sometype { get { return sometype.DoSomething(); } } //C
public sometype sometype { get { return sometype.Trim(); } } //D
  • A -> 错误(没有方法 DoSomething())
  • B -> 作品
  • C -> 作品
  • D -> 错误(没有方法 Trim())

从更适用的角度来看

(如果 XSD 让你感到厌烦,你可能想跳过这个):

我目前正在尝试让 LINQ to XSD 正常工作。在我的 XSD 文件中有这样的 xs:elements:

<xs:element name="car" type="car">

'car' 类型被定义为这样的 simpleType
(可能还有一些限制,但本质上就是这样):

<xs:simpleType name="car">
 <xs:restriction base="xs:string" />
</xs:simpleType>

所以很自然地 LINQ to XSD 会生成如下所示的代码:

public string car {
    get {
        XElement x = this.GetElement(XName.Get("car", ""));
        return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype);
    }
    set {
        this.SetElementWithValidation(XName.Get("car", ""), value, "car", car.TypeDefinition);
    }
}

但是由于上述问题,这不会编译。

4

2 回答 2

5

您应该完全限定类型的命名空间。

如果该类型没有命名空间,那么您可以在它前面加上前缀global::(无论如何在 C# 中)。

于 2009-10-06T13:07:48.413 回答
2

您可以查看 C# 规范以获取有关此行为的更多信息。这是描述它的章节的开头:

7.3 成员查找
A member lookup is the process whereby the meaning of a name in the context of a type is determined. A member lookup can occur as part of evaluating a simple-name (§7.5.2) or a member-access (§7.5.4) in an expression. If the simple-name or member-access occurs as the simple-expression of an invocation-expression (§7.5.5.1), the member is said to be invoked. If a member is a method or event, or if it is a constant, field or property of a delegate type (§15), then the member is said to be invocable. Member lookup considers not only the name of a member but also the number of type parameters the member has and whether the member is accessible. For the purposes of member lookup, generic methods and nested generic types have the number of type parameters indicated in their respective declarations and all other members have zero type parameters.

于 2009-10-06T13:09:45.573 回答