从通用引用类型获取枚举或静态属性
因此,如果 class
中有一个名为 Bar
的 enum
属性,为什么我无法访问该 enum
属性或在这种情况下 type
的任何 static
属性。我隐式声明
属于 type
Bar
。只是想知道这是否只是泛型或 enum
type
本身的限制。
public class Foo<T> where T : Bar
{
public Foo()
{
// This obviously works
var car = Bar.Cars.Honda;
var name = Bar.Name;
// Why can't I do this ?
var car2 = T.Cars.Toyota;
var name2 = T.Name;
}
}
public class Bar
{
public static string Name { get; set; }
public enum Cars
{
Honda,
Toyota
};
}
更新
在@Frederik Gheysels的回答中,提到如果我有一个简单地从Bar
派生的类
,我无法访问 enum
或 base
的任何 static
。这是不正确的,这可以编译并运行。
public class Foo : Bar
{
public Foo()
{
// This all works
var address = this.Address;
var car = Foo.Cars.Honda;
var name = Foo.Name;
}
}
public class Bar
{
public static string Name { get; set; }
public string Address { get; set; }
public enum Cars
{
Honda,
Toyota
}
}
So if there is an enum
property in a class
called Bar
, why can't I access the enum
property or any static
property of type
<T>
in this situation. I am implicitly declaring that <T>
is of type
Bar
. Just wanted to know if it's simply a limitation of Generics or the enum
type
itself.
public class Foo<T> where T : Bar
{
public Foo()
{
// This obviously works
var car = Bar.Cars.Honda;
var name = Bar.Name;
// Why can't I do this ?
var car2 = T.Cars.Toyota;
var name2 = T.Name;
}
}
public class Bar
{
public static string Name { get; set; }
public enum Cars
{
Honda,
Toyota
};
}
UPDATED
In @Frederik Gheysels's answer, it's mentioned that if I have a class
that is simply derived from Bar
that I wouldn't have access to the enum
or any static
of the base
. That is not correct, this compiles and works.
public class Foo : Bar
{
public Foo()
{
// This all works
var address = this.Address;
var car = Foo.Cars.Honda;
var name = Foo.Name;
}
}
public class Bar
{
public static string Name { get; set; }
public string Address { get; set; }
public enum Cars
{
Honda,
Toyota
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
Cars
枚举是Bar
类内的嵌套类型。它不是Bar
的成员属性/方法。因此,这是不可能的。
Cars 只是 Bar 的嵌套类型。当您创建另一个从 Bar 派生的类(我们将其称为
Bar2
)时,您也将无权访问Bar2.Cars
,因为不会创建该类型。嵌套类型不是实例成员,因此不会被继承。your
Cars
enum, is a nested type inside classBar
. It is not a member property / method ofBar
.Therefore, it is not possible.
Cars is just a nested type of Bar. When you create another class, which derives from Bar, lets call it
Bar2
, you will not have access toBar2.Cars
neither, since that type will not be created. Nested types are not instance members, and are thus not inherited.一个可能的解决方法是允许 Foo继承自
Bar
以公开静态成员。要访问静态成员Name
,您需要提供一个虚拟访问器 此处讨论。A potential workaround is to allow
Foo<T>
to inherit fromBar
to expose the static members. To access the static memberName
, you need to provide a virtual accessor as discussed here.