Is it possible to access an instance variable via a static method?
In C#, is it possible to access an instance variable via a static method in different classes without using parameter passing?
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);
}
}
Sure, you could pass an instance as a parameter to the method. Like:
public static void DoSomething(Button b)
{
b.Text = "foo";
}
But it wouldn't be possible to get at any instance variables otherwise.
A static method has no instance to work with, so no. It's not possible without parameter passing.
Another option for you might be to use a static instance of the class (Mark's example shows this method at work) although, from your example, I'm not sure that would solve your problem.
Personally, I think parameter passing is going to be the best option. I'm still not sure why you want to shy away from it.
Yes it can, as long as it has an instance of an object in scope. Singletons for instance, or objects created within the method itself..
Take for example a common scenario :
public static string UserName
{
return System.Web.HttpContext.Current.User.Identity.Name;
}
No you can't.
If you want to access an instance variable then your method by definition should not be static.
精彩评论