我希望创建一个类,并使用初始化类中的一个方法来更改调用实例的属性值。不知怎么的,我脑子里有个结,似乎是我的一个基本思维错误。也许有人能帮我弄清楚。
Class Program
{
...
private void Initialize()
{
Zoo myZoo = new Zoo();
myZoo.Load();
Console.WriteLine(myZoo.ZooName);
}
}
动物园班:
public class Zoo
{
public string ZooName { get; set; }
...
internal void Load()
{
Zoo myZoo = this;
using (StreamReader reader = File.OpenText(@"C:\Areas.json"))
{
JsonSerializer serializer = new JsonSerializer();
myZoo = (Zoo) serializer.Deserialize(reader, typeof(Zoo));
}
}
}
JSON部分工作正常,但是一旦Load()-method结束,myZoo/它就被设置为NULL。是否有可能使用“this”来修改调用类实例的属性值?
发布于 2018-04-25 10:27:38
其他方式,out.you可以使用ref关键字的相同。
Class Program
{
...
private void Initialize()
{
Zoo myZoo = new Zoo();
myZoo.Load(ref myZoo);
Console.WriteLine(myZoo.ZooName);
}
}
public class Zoo
{
public string ZooName { get; set; }
...
internal void Load(ref Zoo myZoo)
{
using (StreamReader reader = File.OpenText(@"C:\Areas.json"))
{
JsonSerializer serializer = new JsonSerializer();
myZoo = (Zoo) serializer.Deserialize(reader, typeof(Zoo));
}
}
}
发布于 2018-04-25 10:14:59
您可能想要在类上创建一个工厂方法。此函数将返回Zoo
的一个新实例,其中包含json文件中的数据。
如下所示:
public class Zoo
{
public string ZooName { get; set; }
...
public static Zoo Init()
{
using (StreamReader reader = File.OpenText(@"C:\Areas.json"))
{
JsonSerializer serializer = new JsonSerializer();
var myZoo = (Zoo) serializer.Deserialize(reader, typeof(Zoo));
return myZoo;
}
}
}
在您的Initialize
函数中,您现在可以创建如下所示的实例:
private void Initialize()
{
var myZoo = Zoo.Init();
Console.WriteLine(myZoo.ZooName);
}
发布于 2018-04-25 10:15:41
您不能set
this
指针。在C#中也没有要过载的赋值操作符。
可以将加载的动物园对象中的所有属性复制到此对象中。
更常见的方法是有一个静态工厂方法为您执行此操作:
public class Zoo
{
public string ZooName { get; set; }
...
public static Zoo Load(string file)
{
using (StreamReader reader = File.OpenText(file))
{
JsonSerializer serializer = new JsonSerializer();
return (Zoo) serializer.Deserialize(reader, typeof(Zoo));
}
}
}
后来这样称呼它:
Zoo z = Zoo.Load(@"C:\Areas.json");
https://stackoverflow.com/questions/50019565
复制相似问题