gpt4 book ai didi

c# - 无法访问我的对象的成员

转载 作者:太空宇宙 更新时间:2023-11-03 21:14:45 25 4
gpt4 key购买 nike

Error : 'object' does not contain a definition for 'lp' and no extension method >'lp' accepting a first argument of type 'object' could be found (are you missing >a using directive or an assembly reference?

如果我尝试从我的对象中获取一个值,我会得到这个...

enter image description here

但是当我在不尝试获取值的情况下运行时,我可以清楚地看到我的对象确实包含 lp...

enter image description here

反序列化的完整代码...

public object Deserialize(Object obj, string path)

{

XmlSerializer serializer = new XmlSerializer(obj.GetType());

StreamReader reader = new StreamReader(path);
obj = serializer.Deserialize(reader);
reader.Close();
return obj;

}

人类...

public class Person
{
public string name { get; set; }
public int age { get; set; }

}

PersonList 类...

public class PersonList

{
public List<Person> lp = new List<Person>();


public void AddPerson(Person p)
{
lp.Add(p);
}
}

这是我发送给公共(public)类 PersonList 的 Person List 的一个实例

{
public List<Person> lp = new List<Person>();


public void AddPerson(Person p)
{
lp.Add(p);
}
}.

UPDATE: I was doing casting before but I will be passing in loads of different types of objects so wanted a generic Deserialize function. is there a way to do this? –

最佳答案

您更新了您的问题,要求进行通用转换,而泛型正是您要找的。

public T Deserialize<T>(T obj, string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));

StreamReader reader = new StreamReader(path);
obj = (T)serializer.Deserialize(reader);
reader.Close();
return obj;
}

关于c# - 无法访问我的对象的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35176717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com