【问题标题】:Is it possible to call an object in C#? [duplicate]是否可以在 C# 中调用对象? [复制]
【发布时间】:2016-05-15 21:53:50
【问题描述】:

是否可以在 C# 中调用类实例? 例如,是否可以这样做?

MyClass myClass = new MyClass();
myClass();

【问题讨论】:

  • 不,这是不可能的。你为什么不自己试试呢?
  • 你希望它做什么?

标签: c# object


【解决方案1】:

从技术上讲,函数可以存储为对象。这些在 .NET 中称为委托。

因此,如果您有某种类型的东西,即像 FuncAction 这样的委托,或者这样可以工作,您可以调用它。我不相信这对于任意类是可能的。

例如:

Func<int, int> doubleIt = (x) => x * 2;
doubleIt(4); 

//or
Action<Object> print = x => Console.WriteLine(x);
print(4);

【讨论】:

    【解决方案2】:

    我不知道你的目标是什么,但你可以这样做:

    Func<MyClass> myClass = () => new MyClass();
    
    // Then you can call this function, which returns a new instance of 'MyClass'
    MyClass newInstance = myClass();
    

    【讨论】:

      猜你喜欢
      • 2016-11-28
      • 1970-01-01
      • 2012-05-13
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 2016-06-19
      相关资源
      最近更新 更多