我对C#很新。我正在更多地了解代表们。当我运行此代码时,我收到以下错误:
字段初始值设定项无法引用该行的非静态字段:
CalArepointer cpointer = CalculateArea;
这是我的计划:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculatearea
{
class Program
{
delegate double CalArepointer(int r);
CalArepointer cpointer = CalculateArea;
static void Main(string[] args)
{
double area = cpointer.Invoke(20);
Console.ReadKey();
}
double CalculateArea(int r)
{
return 3.14 * r * r;
}
}
}
答案 0 :(得分:1)
您应该在cpointer
方法的静态上下文中初始化Main
的值,因为您将要使用它:
class Program
{
delegate double CalArepointer(int r);
CalArepointer cpointer;
static void Main(string[] args)
{
cpointer = CalculateArea;
double area = cpointer.Invoke(20);
Console.ReadKey();
}
double CalculateArea(int r)
{
return 3.14 * r * r;
}
}
答案 1 :(得分:0)
为了在主方法之外初始化cpointer
的值,你想使用Static
成员
class Program
{
delegate double CalArepointer(int r);
static CalArepointer cpointer = CalculateArea;
static double CalculateArea(int r)
{
return 3.14 * r * r;
}
static void Main(string[] args)
{
double area = cpointer.Invoke(20);
Console.WriteLine(area);
Console.ReadKey();
}
}