Skip to main content
 首页 » 编程设计

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

2024年02月05日13findumars

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?

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

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

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

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; 
}