是否可以通过静态方法访问实例变量? [英] Is it possible to access an instance variable via a static method?

查看:44
本文介绍了是否可以通过静态方法访问实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,是否可以通过不同类中的静态方法访问实例变量而不使用参数传递?

In C#, is it possible to access an instance variable via a static method in different classes without using parameter passing?

在我们的项目中,我有一个数据访问层类,它有很多静态方法.在这些方法中,SqlCommand 超时值已被硬编码.在我们框架的另一个类(Dac)中,有许多调用这些静态方法的实例方法.

In our project, I have a Data access layer class which has a lot of static methods. In these methods the SqlCommand timeout value has been hard-coded. In another class(Dac) in our framework there are many instance methods which call these static methods.

我不想使用参数传递编写太多代码.有没有比参数传递更简单的解决方案?

I don't want to code too much using parameter passing. Do you have any other solution which is easier than parameter passing?

推荐答案

是的,可以在不使用参数的情况下从静态方法访问实例变量,但前提是您可以通过声明为静态的内容访问它.示例:

Yes, it is possible to access an instance variable from a static method without using a parameter but only if you can access it via something that is declared static. Example:

public class AnotherClass
{
    public int InstanceVariable = 42;
}

public class Program
{
    static AnotherClass x = new AnotherClass(); // This is static.

    static void Main(string[] args)
    {
        Console.WriteLine(x.InstanceVariable);
    }
}

这篇关于是否可以通过静态方法访问实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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