开发者

C# - use symbols from other class without qualifying with classname

I have declared a bunch of global constants in a class and now want to use these constants in other classes without always having to prefix the constants with the name of the class they have been declared in. Example:

namespace SomeName
{
   public class Constants
   {
      public const int SomeConstant = 1;
   }

   public class SomeClass
   {
      void SomeFunc ()
      {
         int i = Constants.SomeConstant;
      }
   }
}

I would like to omit Constants. from开发者_开发问答 Constants.SomeConstant. Using import SomeName.Constants; didn't work. Is there a way to accomplish what I want? If yes, how would I do it?


No, there's no way you can do that.

Having read your comment ("...importing a class like Math this way shortens mathematical code a bit") I can suggest this wicked code:

class MathCalculations
{
    private Func<double, double, double> min = Math.Min;
    private Func<double, double, double> max = Math.Max;
    private Func<double, double> sin = Math.Sin;
    private Func<double, double> tanh = Math.Tanh;

    void DoCalculations()
    {
        var r = min(max(sin(3), sin(5)), tanh(40));
    }
}


The closest you can get is use a very short namespace alias:

using C = Constants;

C.SomeContant;


Aside from using inheritance (which is a really bad idea; don't do it) there's no way of doing this. (In particular, if you were thinking of trying a using directive alias, that can only alias a namespace or a type, not the member of a type.)

As Oded points out, you can reduce the "Constants" to "C", but personally I wouldn't.


I agree with skeet, but you could:

1) Create a static class

public static class Constants{
    public static const int SomeConstant = 1;
}

2) Add a struct property to SomeClass

public struct Constants{
    public const int SomeConst = 1;
}

Both of these will allow you to have the same code in the SomeFunc() method and allow the code to be easily maintained.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜