public static (const) in a generic .NET class

青春壹個敷衍的年華 提交于 2021-01-26 03:47:20

问题


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.


回答1:


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.




回答2:


Something like this works:

using System;

namespace Demo
{
    public class MyClass // Use a non-generic base class for the non-generic bits.
    {
        public const string MyConstant = "fortytwo";

        public static string MyString()
        {
            return MyConstant;
        }
    }

    public class MyClass<T>: MyClass // Derive the generic class
    {                                // from the non-generic one.
        public void Test(T item)
        {
            Console.WriteLine(MyConstant);
            Console.WriteLine(item);
        }
    }

    public static class Program
    {
        private static void Main()
        {
            Console.WriteLine(MyClass.MyConstant);
            Console.WriteLine(MyClass.MyString());
        }
    }
}

This approach works for any static types or values that you want to provide which do not depend on the type parameter. It also works with static methods too.

(Note: If you don't want anybody to instantiate the base class, make it abstract.)



来源:https://stackoverflow.com/questions/27841936/public-static-const-in-a-generic-net-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!