C# 在C中使用具有非静态方法的委托#
问和你一样的问题 从而结束这场战争 所以我使用@Adam Marshall的解决方案,它是有效的,但一旦我开始使用它,即C# 在C中使用具有非静态方法的委托#,c#,delegates,C#,Delegates,问和你一样的问题 从而结束这场战争 所以我使用@Adam Marshall的解决方案,它是有效的,但一旦我开始使用它,即Testit(): 它开始出现以下错误: 非静态字段、方法或属性需要对象引用 你可以。 如何修复它?(如果可能的话,请修复它,而不是引导我到其他帖子,我已经读过了,但无法理解它们)Thx 要么一切都是静态的,要么一切都是实例。你会遇到麻烦,因为你在混搭 一切都是静态的: using System; public class TestClass { private de
Testit()
:
它开始出现以下错误:
非静态字段、方法或属性需要对象引用
你可以。
如何修复它?(如果可能的话,请修复它,而不是引导我到其他帖子,我已经读过了,但无法理解它们)Thx 要么一切都是静态的,要么一切都是实例。你会遇到麻烦,因为你在混搭 一切都是静态的:
using System;
public class TestClass
{
private delegate void TestDelegate();
static TestDelegate testDelegate; //<-- static
static TestClass() //<-- static
{
testDelegate = new TestDelegate(MyMethod);
}
public static void Testit()
{
testDelegate();
}
private static void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
要么一切都是静态的,要么一切都是实例。你会遇到麻烦,因为你在混搭 一切都是静态的:
using System;
public class TestClass
{
private delegate void TestDelegate();
static TestDelegate testDelegate; //<-- static
static TestClass() //<-- static
{
testDelegate = new TestDelegate(MyMethod);
}
public static void Testit()
{
testDelegate();
}
private static void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
您可以使用操作C#内部委托。这样,您就不必指定委托。然后在静态方法中,您可以重新创建对象
using System;
public class TestClass
{
Action testDelegate;
public TestClass()
{
testDelegate = new Action(MyMethod);
}
public static void Testit()
{
TestClass ts = new TestClass();
ts.testDelegate();
}
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
输出:
Hello World
Foobar
您可以使用操作C#内部委托。这样,您就不必指定委托。然后在静态方法中,您可以重新创建对象
using System;
public class TestClass
{
Action testDelegate;
public TestClass()
{
testDelegate = new Action(MyMethod);
}
public static void Testit()
{
TestClass ts = new TestClass();
ts.testDelegate();
}
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
输出:
Hello World
Foobar
我不知道你怎么会用这段代码出错。这是试图从静态成员内部使用非静态成员,这是不允许的。调用实例成员需要一个实例。小提琴产生了一个错误,说需要一个实例。我不知道你怎么会用这段代码得到这个错误。这是试图从静态成员内部使用非静态成员,这是不允许的。调用实例成员需要一个实例。小提琴产生了一个错误,表示需要一个实例。感谢@StuartSmith的回答,我选择了另一个,因为这是一个我能理解的答案(我不知道
操作
)。感谢@StuartSmith的回答,我选择了另一个,因为这是一个我能理解的答案(我不知道操作
)