无法读取一个类的实例常量? [英] Can't read a const in a class instance?
问题描述
我感到十分诧异,当编译器抱怨这一点:
I was mildly surprised when the compiler complained about this:
public class UsefulClass
{
public const String RatingName = @"Ratings\rating";
}
public class OtherClass
{
public void SomeFunc()
{
UsefulClass useful = new UsefulClass();
String rating = useful.RatingName;
}
}
编译器说的静态成员不能与实例引用访问;同一个类型名限定它,而不是的
这是没有问题的,字符串等级= UsefulClass .RatingName;
工作正常。我只是好奇的想法是这背后是什么?我有一个公共的类的实例上有一个公共不变,为什么我不能获取数据这样?
This isn't a problem, String rating = UsefulClass.RatingName;
works fine. I'm just curious what the thinking is behind this? I have an instance of a public class with a public constant on it, why can't I get the data this way?
推荐答案
由于常数只是没有实例成员;他们是静态绑定到各自的类型。以同样的方式使用情况下,你不能调用静态方法,你不能访问使用实例类的常量。
Because constants just aren't instance members; they're statically bound to their respective types. In the same way you can't invoke static methods using instances, you can't access class constants using instances.
如果你需要获得恒定关断的实例,不需要知道它的类型第一手的,我想你可以根据其类型与反思做到这一点。
If you need to get a constant off an instance without knowing its type first-hand, I suppose you could do it with reflection based on its type.
如果你想补充一点,不能被修改的成员但涉及的情况下,你可能想只读字段或属性来代替。
If you're trying to add a member that can't be modified but pertains to instances, you probably want read-only fields or properties instead.
这篇关于无法读取一个类的实例常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!