[英]C# class name - method name collision
Say I have a class named 'Foo', with some static member, and in some other class (which is under the same namespace) there is a factory method with the same name, which uses this member: 假设我有一个名为“ Foo”的类,具有一些静态成员,而在其他一些类(位于相同名称空间下)中,有一个具有相同名称的工厂方法,该方法使用该成员:
namespace MyNamespace
{
public class Foo
{
public static bool Invert = false;
public int A {get; set;}
....
}
public class FooFactory
{
public Foo Foo(int A)
{
if(Foo.Invert) // --> this gives the 'is a 'method', which is not valid in the given context' Error
return new Foo(-A);
else
return new Foo(A);
}
}
}
(Some code was omitted for brevity). (为简洁起见,省略了一些代码)。 Obviously, the compiler does not interprets the 'Foo' in the 'if' clause as the class 'Foo', but as the factory method.
显然,编译器不会将“ if”子句中的“ Foo”解释为类“ Foo”,而是解释为工厂方法。 Assuming I'm not in liberty to change the class' name nor the factory method's name, can I force the compiler to recognize 'Foo' as a class name rather than the method name?
假设我无权更改类名或工厂方法名,可以强制编译器将“ Foo”识别为类名而不是方法名吗?
EDIT Sorry for not mentioning this earlier - both classes are in the same namespace, therefore MyNamespace.Foo.Invert does not do the trick. 编辑抱歉,您之前没有提到它-两个类都在同一个命名空间中,因此MyNamespace.Foo.Invert不能解决问题。
Your code does not work because what you actually try is to access MyNamespace.FooFactory.Foo
method as if it was a class. 您的代码无效,因为您实际尝试的是访问
MyNamespace.FooFactory.Foo
方法,就像它是一个类一样。 If you specify MyNamespace.Foo
you will specify the class which was intended. 如果指定
MyNamespace.Foo
,则将指定所需的类。
namespace MyNamespace
{
public class Foo
{
public static bool Invert = false;
public int A {get; set;}
....
}
public class FooFactory
{
public Foo Foo(int A)
{
if(MyNamespace.Foo.Invert)
return new MyNamespace.Foo(-A);
else
return new MyNamespace.Foo(A);
}
}
}
This will work. 这将起作用。
Concerning your EDIT, MyNamespace.FooFactory.Foo
and MyNamespace.Foo
are not the same. 关于您的EDIT,
MyNamespace.FooFactory.Foo
和MyNamespace.Foo
是不同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.