[英]Syntax for declaring an initialized dictionary Model Property in ASP.NET MVC?
I'm attempting to add a dictionary property in one of my model classes that has a set list of key value pairs. 我试图在我的一个模型类中添加一个词典属性,该类具有一组键值对列表。 However, I don't know how to declare this with the {get; 但是,我不知道如何使用{get; set;} syntax that signals this is a model property and not a simple field. set;}表示这是模型属性而不是简单字段的语法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ContosoUniversity.Models
{
public class Profile
{
//classNameID or ID is interpreted by EF as PK.
public int ID { get; set; }
public string UserName { get; set; }
public string Age { get; set; }
public string Location { get; set; }
public string Gender { get; set; }
//How to declare this property with get, set and initialized key/val pairs?
public string Dictionary<string, string> ProfileDetails =
new Dictionary<string, string>()
{
{"HighSchool", ""},
{"UndergraduateSchool", ""},
{"GraduateSchool", ""},
}
}
} }
Declare a property and the you can use constructor to initialize it. 声明一个属性,您可以使用构造函数对其进行初始化。
public class Profile
{
public Dictionary<string, string> ProfileDetails {get; set;}
public Profile()
{
ProfileDetails = new Dictionary<string, string>()
{
{"HighSchool", ""},
{"UndergraduateSchool", ""},
{"GraduateSchool", ""},
};
}
}
Declaration: 宣言:
class Profile{
private Dictionary<string,string> _profileDetails;
public Dictionary<string,string> ProfileDetails { get { return _profileDetails; } }
public Profile() { _profileDetails = new Dictionary<string,string>(); }
}
Usage: 用法:
var myProfile = new Profile();
myProfile.ProfileDetails["key2"] = "Something";
public Dictionary<string, string> ProfileDetails {get; set};
//An automatic property syntax. //自动属性语法。 This property will be auto backed by a field of the same type ie Dictionary 此属性将由相同类型的字段(即字典)自动支持
For initialization use class constructor to add keyValuePairs in it. 对于初始化,请使用类构造函数在其中添加keyValuePairs。
public Profile()
{
ProfileDetails = new Dictionary<string, string>(){
{"key01", "value01"},
{"key02", "value02"},
{"key03", "value03"}
}; //This syntax is called collection initializer.
}
In this way you can achieve your target here. 这样,您可以在这里实现目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.