实例方法需要什么来访问C#中的静态成员 [英] What is the need of instance methods access static members in C#

查看:111
本文介绍了实例方法需要什么来访问C#中的静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对实例方法访问静态成员的需求有疑问.

通常静态成员共享给该类的所有实例,但是为什么instance

方法访问静态成员.实例方法与类
的实例相关联
已经共享了静态成员,但是为什么要特殊访问静态成员呢?

成员被访问.


请帮助我

谢谢你

我尝试过的事情:

我对实例方法访问静态成员的需求有疑问.

通常静态成员共享给该类的所有实例,但是为什么instance

方法访问静态成员.实例方法与类
的实例相关联
已经共享了静态成员,但是为什么要特殊访问静态成员呢?

I have doubt on what is the need of instance methods access static member.

Generally static members are share to the all instance of the class but why instance

methods access static members.instance methods are associated with instance of class

already static members are shared but why specially and what is need of access static

members are accessed.


please help me

thank u

What I have tried:

I have doubt on what is the need of instance methods access static member.

Generally static members are share to the all instance of the class but why instance

methods access static members.instance methods are associated with instance of class

already static members are shared but why specially and what is need of access static

members are accessed.

推荐答案

可以在没有类实例的情况下随时访问静态成员-这不会阻止实例方法访问静态信息. br/> 昨天,请参阅上一个类似的问题的答案:何时使用静态方法C# [ ^ ]

Static members can be accessed at any time without an instance of the class - that doesn''t stop instance methods from accessing static information.
See the answers to your previous - rather similar - question yesterday: When to use static methods C#[^]

报价:

但是,静态方法仅执行静态字段操作还是不执行,即静态方法是否可以执行该操作的访问实例字段?

Thank u but static method perform the operation only static fields or not i.e static methods are access instance fields for perform the operation is possible?



静态方法只能访问静态字段,属性,方法等-它们无法访问实例的任何内容,因为它们在运行时不存在任何实例:没有this引用可以通过来访问实例数据.
唯一的例外是将实例传递给静态方法或静态方法创建其自己的实例时:



Static methods can only access static fields, properties, methods, etc. - they cannot access instance anything because there is no instance present when they are running: there is no this reference to access instance data via.

The only exceptions to that are when an instance is pass to a static method, or the static method creates it''s own instance:

public void DoSomething()
   {
   Console.WriteLine(this.Text);
   }
public static void MyMethod(MyClass mc)
   {
   mc.DoSomething();
   }


public void DoSomething()
   {
   Console.WriteLine(this.Text);
   }
public static void MyMethod()
   {
   MyClass mc = new MyClass();
   mc.DoSomething();
   }


这篇关于实例方法需要什么来访问C#中的静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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