具有相同名称的静态和实例方法? [英] Static and Instance methods with the same name?

查看:26
本文介绍了具有相同名称的静态和实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中有一个包含静态和非静态接口的类.同名同名的类中可以有静态方法和非静态方法吗?

I have a class with both a static and a non-static interface in C#. Is it possible to have a static and a non-static method in a class with the same name and signature?

当我尝试这样做时出现编译器错误,但出于某种原因,我认为有一种方法可以做到这一点.我错了还是没有办法在同一个类中同时拥有静态和非静态方法?

I get a compiler error when I try to do this, but for some reason I thought there was a way to do this. Am I wrong or is there no way to have both static and non-static methods in the same class?

如果这是不可能的,有没有什么好的方法可以实现这样的东西,可以普遍应用于任何情况?

If this is not possible, is there a good way to implement something like this that can be applied generically to any situation?

编辑
从我收到的回复来看,很明显没有办法做到这一点.我打算使用不同的命名系统来解决这个问题.

EDIT
From the responses I've received, it's clear that there is no way to do this. I'm going with a different naming system to work around this problem.

推荐答案

不,你不能.限制的原因是静态方法也可以从非静态上下文调用,而无需预先添加类名(因此 MyStaticMethod() 而不是 MyClass.MyStaticMethod()).如果您同时拥有两者,编译器将无法判断您正在寻找哪一个.

No you can't. The reason for the limitation is that static methods can also be called from non-static contexts without needing to prepend the class name (so MyStaticMethod() instead of MyClass.MyStaticMethod()). The compiler can't tell which you're looking for if you have both.

静态方法和非静态方法可以同名,但不同的参数遵循与方法重载相同的规则,只是不能有完全相同的签名.

You can have static and non-static methods with the same name, but different parameters following the same rules as method overloading, they just can't have exactly the same signature.

这篇关于具有相同名称的静态和实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆