问题描述
在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);
}
}
这篇关于是否可以通过静态方法访问实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!