C# C类属性';平局';归档?(参见Perl::Tie)
在perl中,有一种相当简单的方法将数据结构绑定到文件,无论是字符串、哈希(C#中的字典)还是简单的数组/列表 我已经用C#拼凑了自己的半途而废的解决方案,但我想知道是否有一种更内在的方式来实现这一功能 编辑以回应下面的评论——直接的问题是:是否有一种内置的方式将类/字典“绑定”到文件,以便任何一个类/字典的更改都反映在另一个类/字典中?(没有像下面那样做) (绑定字典意味着字典中的任何更改都会立即反映/更新到文件中,如果对象已经存在,则声明绑定变量将从磁盘加载该对象;请参阅) 我的伪领带等级如下:C# C类属性';平局';归档?(参见Perl::Tie),c#,perl,data-structures,persistent,tie,C#,Perl,Data Structures,Persistent,Tie,在perl中,有一种相当简单的方法将数据结构绑定到文件,无论是字符串、哈希(C#中的字典)还是简单的数组/列表 我已经用C#拼凑了自己的半途而废的解决方案,但我想知道是否有一种更内在的方式来实现这一功能 编辑以回应下面的评论——直接的问题是:是否有一种内置的方式将类/字典“绑定”到文件,以便任何一个类/字典的更改都反映在另一个类/字典中?(没有像下面那样做) (绑定字典意味着字典中的任何更改都会立即反映/更新到文件中,如果对象已经存在,则声明绑定变量将从磁盘加载该对象;请参阅) 我的伪领带等级如
#region options
private float _Opacity;
public float Opacity {
get {
return Opacity;
}
set {
_Opacity = value;
this.Save();
}
}
private Font _Font;
public Font Font {
get {
return _Font;
}
set {
_Font = value;
this.Save();
}
}
private Color _FontColor;
public Color FontColor {
get {
return _FontColor;
}
set {
_FontColor = value;
this.Save();
}
}
private Color _BGColor;
public Color BGColor {
get {
return _BGColor;
}
set {
_BGColor = value;
this.Save();
}
}
private Point _Location;
public Point Location {
get {
return _Location;
}
set {
_Location = value;
this.Save();
}
}
private Size _Size;
public Size Size {
get {
return _Size;
}
set {
_Size = value;
this.Save();
}
}
private ushort _HistoryLines;
public ushort HistoryLines {
get {
return _HistoryLines;
}
set {
_HistoryLines = value;
this.Save();
}
}
private ChatType _ChatModes;
public ChatType ChatModes {
get {
return _ChatModes;
}
set {
_ChatModes = value;
this.Save();
}
}
private bool _Debugging;
public bool Debugging {
get {
return _Debugging;
}
set {
_Debugging = value;
this.Save();
}
}
#endregion options
private FontConverter FontConvert;
private FileInfo SettingsFile;
private MLogConf() {
}
public MLogConf(string stateFile) {
FontConvert = new FontConverter();
try {
if (!Directory.Exists(Path.GetDirectoryName(stateFile)))
Directory.CreateDirectory(Path.GetDirectoryName(stateFile));
if (!File.Exists(stateFile)) {
FileStream fs = File.Create(stateFile);
fs.Close();
}
SettingsFile = new FileInfo(stateFile);
if (SettingsFile.Length == 0) {
this.SetDefaultOptions();
} else {
if (!this.Load()) {
throw new FileLoadException("Couldn't load settings file");
}
}
} catch (Exception ex) {
Trace.Write($"Failed to create MLogConf({nameof(stateFile)}) {ex.Message + Environment.NewLine + ex.StackTrace}");
}
}
private bool Load() {
if (SettingsFile == null)
return false;
try {
byte[] data = File.ReadAllBytes(SettingsFile.FullName);
using (MemoryStream m = new MemoryStream(data)) {
using (BinaryReader reader = new BinaryReader(m)) {
_Opacity = reader.ReadSingle();
_Font = (Font)(FontConvert.ConvertFromString(Encoding.ASCII.GetString(Convert.FromBase64String(reader.ReadString()))));
_FontColor = Color.FromArgb(reader.ReadInt32());
_BGColor = Color.FromArgb(reader.ReadInt32());
_Location = new Point(reader.ReadInt32(), reader.ReadInt32());
_Size = new Size(reader.ReadInt32(), reader.ReadInt32());
_HistoryLines = reader.ReadUInt16();
_ChatModes = (ChatType)reader.ReadInt32();
_Debugging = reader.ReadBoolean();
}
}
} catch (Exception e) {
Trace.WriteLine($"Exception reading binary data: {e.Message + Environment.NewLine + e.StackTrace}");
return false;
}
return true;
}
private bool Save() {
try {
using (FileStream fs = new FileStream(SettingsFile.FullName, FileMode.Create)) {
using (BinaryWriter writer = new BinaryWriter(fs)) {
writer.Write(_Opacity);
writer.Write(Convert.ToBase64String(Encoding.ASCII.GetBytes((string)FontConvert.ConvertTo(Font, typeof(string)))));
writer.Write(_FontColor.ToArgb());
writer.Write(_BGColor.ToArgb());
writer.Write(_Location.X);
writer.Write(_Location.Y);
writer.Write(_Size.Width);
writer.Write(_Size.Height);
writer.Write(_HistoryLines);
writer.Write((int)_ChatModes);
writer.Write(_Debugging);
}
}
} catch (Exception e) {
Trace.WriteLine($"Exception writing binary data: {e.Message + Environment.NewLine + e.StackTrace}");
return false;
}
return true;
}
private bool SetDefaultOptions() {
this._BGColor = Color.Black;
this._ChatModes = ChatType.Alliance | ChatType.Emote | ChatType.FreeCompany | ChatType.Linkshell | ChatType.Party | ChatType.SayShoutYell | ChatType.Tell;
this._Opacity = 1f;
this._Font = new Font("Verdana", 50);
this._FontColor = Color.CornflowerBlue;
this._Location = new Point(100, 400);
this._Size = new Size(470, 150);
this._HistoryLines = 512;
this._Debugging = false;
return this.Save();
}
我想您正在寻找一种在文件中存储类实例的简单方法 序列化是将对象转换为字节流以存储对象或将其传输到内存、数据库或文件的过程。它的主要目的是保存对象的状态,以便能够在需要时重新创建它。相反的过程称为反序列化 不久前,我为C#找到的最短解决方案是Newtonsoft提供的Json.NET,可作为NuGet软件包使用。它将为您完成所有的“长类属性到字符串代码”,并为您留下准备好写入文件的字符串。 官方网站可以提供代码示例: 保存到文件:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }
从文件中读取:
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
stringjson=@”{
“名字”:“坏男孩”,
“发布日期”:“1995-4-7T00:00:00”,
“流派”:[
“行动”,
“喜剧”
]
}";
Movie m=JsonConvert.DeserializeObject(json);
字符串名称=m.名称;
//坏小子
那么问题是什么?代码是否与此问题相关?我的代码是一个冗长的示例,说明了我所追求的。。具体来说,我要寻找的是一种内置的.NET方式,将结构绑定到磁盘上的文件。(另外,将代码留给其他正在寻找此功能的人,因为它可能会被证明对其他人有用。)绑定散列就是为对象提供散列的接口。在C#中,字典是对象,因此您只需创建一个实现IDictionary
的类即可。我知道序列化,并试图避免它。。这和我已经在做的事情没什么不同,这是我不想要的。我正在尝试获取一个存在于磁盘上的活动对象,任何访问基本上都会重定向到存储在磁盘上的对象。无需每次更新对象时调用Object.Serialize(文件等)。。所以简而言之,我猜没有本地(例如,没有外部libs)方法来实现这一点?听起来类似于内存映射文件。试试这个:我没有考虑过使用MMF,尽管以我自己有限的经验,我不确定它是否会产生与我试图实现的功能完全相同的功能,但我还是会尝试一下。如果你有时间,你能用一个例子来更新你的答案吗?@ MisterNad可以给你更多的代码示例。我只是在读MMF的同时试图从C++应用程序到C应用程序建立可靠的内存交换。我最终得到了一个解决方案,使用进程间内存读取,而不使用文件。@如果您不需要经常更改磁盘存储,那么编写一个类来同步您的活动对象与文件,如果(它被更改了,并且是偶尔,比如说每秒一次)会花费更少的时间。