通用.NET类中的公共静态(const) [英] public static (const) in a generic .NET class

查看:41
本文介绍了通用.NET类中的公共静态(const)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不指定(ad-hoc)类型的情况下,是否有语法技巧可以获取泛型类中的常量?

 公共类MyClass< T> {公共常量字符串MyConstant ="fortytwo";}//我尝试避免使用此类型规范.var didwork = MyClass< object> .MyConstant;//语法类似于我要完成的语法.var didnotwork = MyClass.MyConstant; 

有一个关于静态变量(常量)没有在不同类型之间共享的警告,例如 MyClass< object> MyClass< int> ,但是我的问题是关于可能可用的语法技巧.

解决方案

使用非泛型抽象父类.

 公共抽象类MyClass{公共常量字符串MyConstant ="fortytwo";}公共类MyClass< T>: 我的课{//东西}var doswork = MyClass.MyConstant; 

当然,这是因为有一定的原因需要将常量作为泛型类的一部分;如果它具有公共可访问性,那么我看不出您为什么不将其放在单独的类中的原因.

对于您制作的每个 泛型类,都有一个非泛型的抽象父类是一个好主意;泛型类实际上是特定子类型类的模板,而不是真正的父类,因此拥有真正的非泛型父类可以使某些技术(例如,但不仅限于此)更加容易.

Is there a syntax trick to get to the constant in a generic class without specifying an (ad-hoc) type?

public class MyClass<T>{
    public const string MyConstant = "fortytwo";
}

// I try to avoid this type specification.
var doeswork = MyClass<object>.MyConstant;  

// Syntax similar to what I'd like to accomplish.
var doesnotwork = MyClass.MyConstant;  

There is a caveat about the static variable (constant) not being shared between different types like MyClass<object> and MyClass<int> but my question is about possible available syntax trick.

解决方案

Use a non-generic abstract parent class.

public abstract class MyClass
{
   public const string MyConstant = "fortytwo";
}

public class MyClass<T> : MyClass
{
   // stuff
}

var doeswork = MyClass.MyConstant; 

That of course assumes that there's some reason the constant needs to be part of the generic class; if it has public accessibility, I'm not seeing a reason why you wouldn't just put it in a separate class.

Having a non-generic abstract parent class is a good idea for every generic class you make; the generic class is actually a template for the specific subtype classes, rather than a true parent, so having a true non-generic parent can make some techniques (such as, but certainly not limited to, this one) a lot easier.

这篇关于通用.NET类中的公共静态(const)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆