C#类引用,而不是实例的引用 [英] c# class reference as opposed to instance reference
问题描述
我可以在本地引用在C#中的一类,而不是一个类的实例?下面的代码将无法编译,但作为一个例子,是这样的:
Can I locally reference a class in C#, instead of an instance of a class? The following code won't compile but, as an example, something like:
void someFunc()
{
var a = System.Math;
var b = a.Abs(4);
}
编辑:在真正的程序它不是System.Math类和我米想构造类,并返回所构造的值。我没有原来认为在这我想使用类的背景下将相应和,也许它不应该是。
edit: In the real program it's not the System.Math class and I'm wanting to construct the class and return the constructed value. I didn't think originally that the context in which I wanted to use the class would be relevent, and probably it shouldn't be.
Anastasiosyal有一个有趣的想法使用本地代表做。
Anastasiosyal has an interesting idea with using a local Delegate to do it.
推荐答案
您不能分配的变量的静态类的值。现在的问题是的为什么的你会想这样做,还有,你可以解决你的问题。
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);
这篇关于C#类引用,而不是实例的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!