C# - 使用其他类的符号而不用类名限定

问题描述 投票:0回答:5

我在一个类中声明了一堆全局常量,现在想在其他类中使用这些常量,而不必总是在常量前面加上声明它们的类的名称。示例:

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

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

我想从

Constants.
中省略
Constants.SomeConstant
。使用
import SomeName.Constants;
不起作用。有办法实现我想要的吗?如果是的话我该怎么做?

c#
5个回答
3
投票

不,你无法做到这一点。

读完你的评论后(“...以这种方式导入像 Math 这样的类可以稍微缩短数学代码”)我可以建议这个邪恶的代码:

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));
    }
}

1
投票

您可以获得的最接近的是使用非常短的命名空间别名

using C = Constants;

C.SomeContant;

0
投票

除了使用继承(这是一个真的坏主意;不要这样做)之外,没有其他办法可以做到这一点。 (特别是,如果您正在考虑尝试使用 using 指令别名,那么它只能为名称空间或type命名,而不是类型的member。)

正如 Oded 指出的,你可以将“常量”减少为“C”,但我个人不会。


0
投票

我同意双向飞碟,但你可以:

1)创建静态类

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

2)向 SomeClass 添加结构体属性

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

这两者都将允许您在 SomeFunc() 方法中拥有相同的代码,并且使代码易于维护。


0
投票

更新: 从 C# 6.0 开始,您可以通过

using static
关键字来做到这一点:

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


using static Constants;   
public class SomeClass
{
   void SomeFunc ()
   {
      int i = SomeConstant;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.