This question already has an answer here:
这个问题在这里已有答案:
- Overloading function call operator in C# 7 answers
在C#7答案中重载函数调用操作符
Is it possible to call a class instance in C#? For example, is it possible to do this?
是否可以在C#中调用类实例?例如,是否可以这样做?
MyClass myClass = new MyClass();
myClass();
2 个解决方案
#1
1
Technically, functions can be stored as objects. These are called delegates in .NET.
从技术上讲,函数可以存储为对象。这些在.NET中称为委托。
So if you have something that's of type i.e. a delegate like Func
or Action
or such that would work, you can call it. I don't believe this is possible for arbitrary classes.
因此,如果您拥有类型的东西,例如像Func或Action这样的委托,或者可以使用它,那么您可以调用它。我不相信这对任意类来说是可能的。
For example:
Func<int, int> doubleIt = (x) => x * 2;
doubleIt(4);
//or
Action<Object> print = x => Console.WriteLine(x);
print(4);
#2
0
I don't know what is your goal with this but you can do something like this:
我不知道你的目标是什么,但你可以这样做:
Func<MyClass> myClass = () => new MyClass();
// Then you can call this function, which returns a new instance of 'MyClass'
MyClass newInstance = myClass();
#1
1
Technically, functions can be stored as objects. These are called delegates in .NET.
从技术上讲,函数可以存储为对象。这些在.NET中称为委托。
So if you have something that's of type i.e. a delegate like Func
or Action
or such that would work, you can call it. I don't believe this is possible for arbitrary classes.
因此,如果您拥有类型的东西,例如像Func或Action这样的委托,或者可以使用它,那么您可以调用它。我不相信这对任意类来说是可能的。
For example:
Func<int, int> doubleIt = (x) => x * 2;
doubleIt(4);
//or
Action<Object> print = x => Console.WriteLine(x);
print(4);
#2
0
I don't know what is your goal with this but you can do something like this:
我不知道你的目标是什么,但你可以这样做:
Func<MyClass> myClass = () => new MyClass();
// Then you can call this function, which returns a new instance of 'MyClass'
MyClass newInstance = myClass();