【发布时间】:2018-09-21 23:41:07
【问题描述】:
首先,请在断定它是Member '<method>' cannot be accessed with an instance reference 的重复之前通读问题。
现在,我的问题有所不同,因为我的静态成员是另一个类:
using System;
public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { Console.WriteLine("Driving"); }
// public static event bool RunOutOfGas;
// Other non-static fields and properties...
}
class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;
public static Automobile A1;
// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
baseline = DateTime.Now.Ticks;
A1 = new Automobile();
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Automobile");
Automobile.Drive();
Console.WriteLine(Automobile.NumberOfWheels);
Console.WriteLine("SimpleClass");
Console.WriteLine(SimpleClass.A1.NumberOfWheels);
Console.WriteLine(SimpleClass.Automobile.NumberOfWheels);
}
}
SimpleClass.A1.NumberOfWheels 或 SimpleClass.Automobile.NumberOfWheels(甚至SimpleClass.NumberOfWheels)都会给我错误。
如何访问SimpleClass下的A1.NumberOfWheels?
结论:所以如果你使用静态类而不是C#简单类型,将无法访问根类(SimpleClass)下的静态成员(A1.NumberOfWheels) ,由于 C# 静态成员访问规则的限制。我问这个问题是因为我认为这是一个明显的设计缺陷,但是,没有人解决这个特定问题并迅速将其扫到地毯下。
可能更大的问题是:您到底想做什么?
@RufusL,好问题。我对静态变量或其用途的理解是在其所有类对象之间共享一个单点真理。用一个非常简单的例子来解释,假设我有一堆个位数的乘数对象,它们负责计算两个个位数的倍数。最快的方法不是每次都计算,而是在它们的静态变量中存储一个二维个位数的倍数表,所以不需要真正的倍数,只需要查找。这将显着提高性能。
现在,
- 这样的静态变量只能是C#预定义的简单类型,不能是我自己定义的类型,这是没有意义的。
- 在一个类中这样的静态变量只能是一个级别的深度,并且不能更深,这也没有多大意义。
【问题讨论】:
-
"甚至
SimpleClass.NumberOfWheels"你为什么认为这应该有效?NumberOfWheels在另一个类中声明... -
除非你做一些特定的事情,否则
static方法和属性应该被完全避免。您似乎习惯于到处使用它们,这可能意味着您“做错了”。在您的情况下,您可能需要一个普通的、实例化的、非静态的Automobile类,并且可能需要一个对它的引用,该引用保存在静态变量中或作为Main()中的局部变量。如果您需要一次处理不止一辆汽车,那么让所有东西都保持静止将是一个大问题。 -
是的,它是重复的。不,只是您使用自己的不同类并使用稍微不同的“路径”来访问有问题的静态成员并不会使其不重复。 (一个简化的等价物 - 我不得不承认,这很愚蠢 - 示例是:“为什么这不起作用:5 * 3/0?它不是另一个关于除以零的问题的重复,因为我先做一个乘法。见...")
-
你有一个 instance 类型的静态成员。您甚至可以在构造函数中新建实例。尝试在
SimpleClass构造函数中执行int x = A1.NumberOfWheels;- 它也不起作用。有关更多信息,请参阅重复的问题... :) -
@RufusL,请告诉我如何在不先新建实例的情况下使用类变量。