आप निम्न वर्ग बना सकते हैं:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Soap;
using System.Reflection;
using System.IO;
namespace SerializeStatic_NET
{
public class SerializeStatic
{
public static bool Save(Type static_class, string filename)
{
try
{
FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public);
object[,] a = new object[fields.Length,2];
int i = 0;
foreach (FieldInfo field in fields)
{
a[i, 0] = field.Name;
a[i, 1] = field.GetValue(null);
i++;
};
Stream f = File.Open(filename, FileMode.Create);
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(f, a);
f.Close();
return true;
}
catch
{
return false;
}
}
public static bool Load(Type static_class, string filename)
{
try
{
FieldInfo[] fields = static_class.GetFields(BindingFlags.Static | BindingFlags.Public);
object[,] a;
Stream f = File.Open(filename, FileMode.Open);
SoapFormatter formatter = new SoapFormatter();
a = formatter.Deserialize(f) as object[,];
f.Close();
if (a.GetLength(0) != fields.Length) return false;
int i = 0;
foreach (FieldInfo field in fields)
{
if (field.Name == (a[i, 0] as string))
{
field.SetValue(null, a[i,1]);
}
i++;
};
return true;
}
catch
{
return false;
}
}
}
}
आप System.Runtime.Serialization.Formatters.Soap के लिए एक संदर्भ परिभाषित करना होगा।
public static class A
{
public static string s;
public static int i;
public static double z;
}
आप नीचे दिए गए कोड का उपयोग हो सकता है::
कहो, अपने कार्यक्रम में आप निम्नलिखित स्थिर वर्ग सहेजना चाहते आप सहेजे गए डेटा लोड करने के लिए चाहते हैं
bool ok = SerializeStatic.Save(typeof(A), "c:\\tests\\a.dat");
(में एक ही कार्यक्रम या किसी अन्य प्रोग्राम में), निम्नलिखित कोड का उपयोग करें:
bool ok2 = SerializeStatic.Load(typeof(A), "c:\\tests\\a.dat");
फ़ील्ड ए, एज़, जीई नए, भारित मूल्य नहीं।
मुझे लगता है कि "सिंगलटन" और "स्थैतिक" के बीच यहां कुछ भ्रम है ... –
"मान लीजिए कि मैं एक्सएमएल ऑब्जेक्ट को व्यवस्थित करता हूं": कौन सा ऑब्जेक्ट? वहां कोई ऑब्जेक्ट नहीं है (यानी कोई उदाहरण नहीं), क्योंकि कक्षा स्थिर –