C# 在asp.net c模型中初始化值#
我有一个Asp.net应用程序在我的模型中的Visual Studio我有这个类C# 在asp.net c模型中初始化值#,c#,asp.net,asp.net-mvc,model,C#,Asp.net,Asp.net Mvc,Model,我有一个Asp.net应用程序在我的模型中的Visual Studio我有这个类 public class Goalkeeper { public static string Name { get; set; } public static string Position { get; set; } public static int Matches { get; set; } public static int Cleansheets { get; s
public class Goalkeeper
{
public static string Name { get; set; }
public static string Position { get; set; }
public static int Matches { get; set; }
public static int Cleansheets { get; set; }
}
有没有一种方法可以让我在模型中设置这些值,这样我就可以在所有不同的视图和控制器动作中使用它们,这样我就不必在控制器的每个动作中都这样设置它们(守门员.Matches=234;),因为这似乎效率很低。您可以:
向模型中添加构造函数,在其中设置初始值:
public class Goalkeeper
{
public Goalkeeper() {
Position = "Goalkeeper";
Matches = 5;
Cleansheets = 0;
}
public static string Name { get; set; }
public static string Position { get; set; }
public static int Matches { get; set; }
public static int Cleansheets { get; set; }
}
或者,直接初始化属性:
public class Goalkeeper
{
public static string Name { get; set; }
public static string Position { get; set; } = "Goalkeeper";
public static int Matches { get; set; } = 5;
public static int Cleansheets { get; set; } = 0;
}
您可以:
向模型中添加构造函数,在其中设置初始值:
public class Goalkeeper
{
public Goalkeeper() {
Position = "Goalkeeper";
Matches = 5;
Cleansheets = 0;
}
public static string Name { get; set; }
public static string Position { get; set; }
public static int Matches { get; set; }
public static int Cleansheets { get; set; }
}
或者,直接初始化属性:
public class Goalkeeper
{
public static string Name { get; set; }
public static string Position { get; set; } = "Goalkeeper";
public static int Matches { get; set; } = 5;
public static int Cleansheets { get; set; } = 0;
}
根据您使用的C#版本,您可以如下方式初始化属性:
public static string Name { get; set; } = "Whatever";
这仅适用于C#6,但取决于您使用的C#版本,您可以如下方式初始化属性:
public static string Name { get; set; } = "Whatever";
这只适用于C#6,尽管public int Matches{get{return This.Matches;}set{This.Matches=234;}}public int Matches{get{return This.Matches;}set{This.Matches=234;}您好。想知道如何用多个寄存器初始化守门员类。@Luisalbertodergadodelaflo您可以创建多个构造函数。例如
公共守门员(字符串名称、字符串位置){…}
你好。想知道如何用多个寄存器初始化守门员类。@Luisalbertodergadodelaflo您可以创建多个构造函数。例如公共守门员(字符串名称、字符串位置){…}