c# class reference as opposed to instance reference

。_饼干妹妹 提交于 2019-12-06 00:05:29

You cannot assign a variable a value of a static class. The question is why would you want to do this, there are probably other ways that you could tackle your problem

e.g. you could use delegates to assign the operation you want to perform:

Func<int,int> operation = Math.Abs; 
// then you could use it like so: 
int processedValue = operation(-1);

You can reference a class:

Type math = typeof(System.Math);

But you cannot call static methods on it using regular dot syntax:

// Wont compile:
math.Abs(5);

If you just want to shorten (and IMHO obfuscate) your code, you can reference classes with aliases via a using directive:

// Untested, but should work
namespace MyUnreadableCode {
    using m = System.Math;
    class Foo {
        public static Int32 Absolut(Int32 a) {
            return m.Abs(a);
        }
    }
}

In c# they're called Types. And you can assign them like:

Type a = typeof(SomeClass);

However, you would have to instantiate it to use it. What I believe you want is a static import like in java, but unfortunately, they do not exist in c#.

Short answer: Not like what you have above.

Andrej Adamenko

In C# 6.0 they introduced a static import feature, which can solve the problem.

using static System.Math;

class MyProgram
{
    static void Main(string[] args)
    {
        var b = Abs(4); // No need to specify the name of Math class
    }
}
Tengiz

As I understand you need to refer to the class with short name? try this (on top of the file, inside using statements section):

using m = System.Math;

later in your code:

m.Abs(...)

Makes sense?

No. It's not possible to treat a Type as a value where instance methods bind to static methods on the original type. In order to do this you would need to construct a new type which forwards it's method calls to the original type.

class MyMath { 
  public int Abs(int i) {
    return Math.Abs(i);
  }
}

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