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

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

问题描述

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

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

在我们的项目中,我有一个里面有很多的静态方法的数据访问层类。在这些方法中的SqlCommand 超时值已经硬codeD。在另一类( 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.

我不想code过多使用参数的传递。你有任何其他的解决方案,这是比参数传递?

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

推荐答案

是的,这可以从一个静态方法访问实例变量,而无需使用参数,但只有当你可以通过该声明为static的东西访问它。例如:

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天全站免登陆