C# 无法使用实例引用访问成员“<方法>”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1100009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Member '<method>' cannot be accessed with an instance reference
提问by Anders
I am getting into C# and I am having this issue:
我正在使用 C# 并且遇到了这个问题:
namespace MyDataLayer
{
namespace Section1
{
public class MyClass
{
public class MyItem
{
public static string Property1{ get; set; }
}
public static MyItem GetItem()
{
MyItem theItem = new MyItem();
theItem.Property1 = "MyValue";
return theItem;
}
}
}
}
I have this code on a UserControl:
我在 UserControl 上有这个代码:
using MyDataLayer.Section1;
public class MyClass
{
protected void MyMethod
{
MyClass.MyItem oItem = new MyClass.MyItem();
oItem = MyClass.GetItem();
someLiteral.Text = oItem.Property1;
}
}
Everything works fine, except when I go to access Property1
. The intellisense only gives me "Equals
, GetHashCode
, GetType
, and ToString
" as options. When I mouse over the oItem.Property1
, Visual Studio gives me this explanation:
一切正常,除非我去访问Property1
. 智能感知只给我 " Equals
, GetHashCode
, GetType
, 和ToString
" 作为选项。当我将鼠标悬停在 上时oItem.Property1
,Visual Studio 给了我这样的解释:
Member
MyDataLayer.Section1.MyClass.MyItem.Property1.getcannot be accessed with an instance reference, qualify it with a type name instead
Member
MyDataLayer.Section1.MyClass.MyItem.Property1.getcannot be accessed with an instance reference, qualify it with a type name instead
I am unsure of what this means, I did some googling but wasn't able to figure it out.
我不确定这意味着什么,我做了一些谷歌搜索,但无法弄清楚。
采纳答案by Mehrdad Afshari
In C#, unlike VB.NET and Java, you can't access static
members with instance syntax. You should do:
在 C# 中,与 VB.NET 和 Java 不同,您不能static
使用实例语法访问成员。你应该做:
MyClass.MyItem.Property1
to refer to that property or remove the static
modifier from Property1
(which is what you probably want to do). For a conceptual idea about what static
is, see my other answer.
引用该属性或static
从中删除修饰符Property1
(这是您可能想要做的)。有关什么static
是概念的概念,请参阅我的其他答案。
回答by SLaks
You can only access static members using the name of the type.
您只能使用类型名称访问静态成员。
Therefore, you need to either write,
因此,你需要要么写,
MyClass.MyItem.Property1
Or (this is probably what you need to do) make Property1
an instance property by removing the static
keyword from its definition.
或者(这可能是您需要做的)Property1
通过static
从其定义中删除关键字来创建实例属性。
Static properties are shared between all instances of their class, so that they only have one value. The way it's defined now, there is no point in making any instances of your MyItem class.
静态属性在其类的所有实例之间共享,因此它们只有一个值。按照现在的定义方式,创建 MyItem 类的任何实例都没有意义。
回答by CarlH
I had the same issue - although a few years later, some may find a few pointers helpful:
我遇到了同样的问题 - 尽管几年后,有些人可能会发现一些有用的提示:
Do not use ‘static' gratuitously!
不要无缘无故地使用“静态”!
Understand what ‘static' implies in terms of both run-time and compile time semantics (behavior) and syntax.
理解“静态”在运行时和编译时语义(行为)和语法方面的含义。
A static entity will be automatically constructed some time before
its first use.A static entity has one storage location allocated, and that is
shared by all who access that entity.A static entity can only be accessed through its type name, not
through an instance of that type.A static method does not have an implicit ‘this' argument, as does an instance method. (And therefore a static method has less execution
overhead – one reason to use them.)Think about thread safety when using static entities.
静态实体将在
首次使用前的一段时间自动构建。静态实体分配了一个存储位置,
并由所有访问该实体的人共享。静态实体只能通过其类型名称访问,而不能通过该类型
的实例访问。静态方法不像实例方法那样具有隐式的“this”参数。(因此静态方法的执行
开销更少——使用它们的一个原因。)使用静态实体时要考虑线程安全。
Some details on static in MSDN:
MSDN中关于静态的一些细节:
回答by Jeremy Thompson
cannot be accessed with an instance reference
不能通过实例引用访问
It means you're calling a STATIC method and passing it an instance. The easiest solution is to remove Static, eg:
这意味着您正在调用 STATIC 方法并将其传递给一个实例。最简单的解决方案是删除静态,例如:
public staticvoid ExportToExcel(IEnumerable data, string sheetName)
{
public staticvoid ExportToExcel(IEnumerable data, string sheetName) {
回答by Julio Nobre
Check whether your code contains a namespace which the right most part matches your static class name.
检查您的代码是否包含最右侧与您的静态类名匹配的命名空间。
Given the a static Barclass, defined on namespace Foo, implementing a method Jumpor a property, chances are you are receiving compiler error because there is also another namespace ending on Bar. Yep, fishi stuff ;-)
给定在命名空间Foo上定义的静态Bar类,实现方法Jump或属性,您可能会收到编译器错误,因为还有另一个命名空间以Bar结尾。是的,fishi 的东西 ;-)
If that's so, it means your using a Using Bar;and a Bar.Jump()call, therefore one of the following solutions should fit your needs:
如果是这样,则意味着您使用了Using Bar;和Bar.Jump()调用,因此以下解决方案之一应该适合您的需求:
- Fully qualify static class name with according namepace, which result on Foo.Bar.Jump()declaration. You will also need to remove Using Bar;statement
- Rename namespace Barby a diffente name.
- 使用相应的命名空间完全限定静态类名,这会导致Foo.Bar.Jump()声明。您还需要删除Using Bar;陈述
- 通过不同的名称重命名命名空间Bar。
In my case, the foollowing compiler error occurred on a EF(Entity Framework) repository project on an Database.SetInitializer()call:
就我而言,在Database.SetInitializer()调用上的EF(实体框架)存储库项目上发生了愚蠢的编译器错误:
Member 'Database.SetInitializer<MyDatabaseContext>(IDatabaseInitializer<MyDatabaseContext>)' cannot be accessed with an instance reference; qualify it with a type name instead MyProject.ORM
This error arouse when I added a MyProject.ORM.Databasenamespace, which sufix (Database), as you might noticed, matches Database.SetInitializerclass name.
添加MyProject.ORM时会出现此错误。您可能已经注意到,数据库命名空间的后缀 ( Database) 与Database.SetInitializer类名匹配。
In this, since I have no control on EF's Databasestatic class and I would also like to preserve my custom namespace, I decided fully qualify EF's Database static class with its namepace System.Data.Entity, which resulted on using the following command, which compilation succeed:
在此,由于我无法控制 EF 的数据库静态类,而且我还想保留我的自定义命名空间,因此我决定使用其命名空间System.Data.Entity完全限定 EF 的数据库静态类,这导致使用以下命令,编译成功:
System.Data.Entity.Database.SetInitializer<MyDatabaseContext>(MyMigrationStrategy)
Hope it helps
希望能帮助到你
回答by Pablo H
I got here googling for C# compiler error CS0176, through (duplicate) question Static member instance reference issue.
我在谷歌上搜索 C# 编译器错误 CS0176,通过(重复)问题Static member instance reference issue。
In my case, the error happened because I had a static method and an extension method with the same name. For that, see Static method and extension method with same name.
就我而言,发生错误是因为我有一个静态方法和一个同名的扩展方法。为此,请参阅具有相同名称的静态方法和扩展方法。
[May be this should have been a comment. Sorry that I don't have enough reputation yet.]
[也许这应该是评论。抱歉,我还没有足够的声望。]
回答by D J
I know this is an old thread, but I just spent 3 hours trying to figure out what my issue was. I ordinarily know what this error means, but you can run into this in a more subtle way as well. My issue was my client class (the one calling a static method from an instance class) had a property of a different type but named the same as the static method. The error reported by the compiler was the same as reported here, but the issue was basically name collision.
我知道这是一个旧线程,但我只花了 3 个小时试图弄清楚我的问题是什么。我通常知道这个错误意味着什么,但你也可以以更微妙的方式遇到这个问题。我的问题是我的客户端类(从实例类调用静态方法的类)具有不同类型的属性,但名称与静态方法相同。编译器报的错误和这里报的一样,但问题基本上是名字冲突。
For anyone else getting this error and none of the above helps, try fully qualifying your instance class with the namespace name. ..() so the compiler can see the exact name you mean.
对于任何其他收到此错误并且上述方法都没有帮助的人,请尝试使用命名空间名称完全限定您的实例类。..() 以便编译器可以看到您的确切名称。
回答by Alan
No need to use static in this case as thoroughly explained. You might as well initialise your property without GetItem()
method, example of both below:
在这种情况下不需要使用静态,正如彻底解释的那样。您也可以在没有GetItem()
方法的情况下初始化您的属性,以下两个示例:
namespace MyNamespace
{
using System;
public class MyType
{
public string MyProperty { get; set; } = new string();
public static string MyStatic { get; set; } = "I'm static";
}
}
Consuming:
消费:
using MyType;
public class Somewhere
{
public void Consuming(){
// through instance of your type
var myObject = new MyType();
var alpha = myObject.MyProperty;
// through your type
var beta = MyType.MyStatic;
}
}
回答by Hedego
YourClassName.YourStaticFieldName
For your static field would look like:
对于您的静态字段将如下所示:
public class StaticExample
{
public static double Pi = 3.14;
}
From another class, you can access the staic field as follows:
从另一个类,您可以按如下方式访问 staic 字段:
class Program
{
static void Main(string[] args)
{
double radius = 6;
double areaOfCircle = 0;
areaOfCircle = StaticExample.Pi * radius * radius;
Console.WriteLine("Area = "+areaOfCircle);
Console.ReadKey();
}
}
回答by Andrew
This causes the error:
这会导致错误:
MyClass aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();
This is the fix:
这是修复:
MyClass.MyCoolStaticMethod();
Explanation:
解释:
You can't call a static method from an instance of an object. The whole point of static methods is to not be tied to instances of objects, but instead to persist through all instances of that object, and/or to be used without any instances of the object.
您不能从对象的实例调用静态方法。静态方法的重点是不与对象的实例绑定,而是在该对象的所有实例中持久化,和/或在没有任何对象实例的情况下使用。