简体   繁体   English

访问对象属性而不转换为类型

[英]Access an object properties without casting to a type

i am using LINQ to entity to return a list of objects 我正在使用LINQ to entity返回一个对象列表

            var st = personsList.Select(p => new
            {
                ID = p.Id,
                Key = p.Key,
                Name = p.Name,
                Address = p.Address,
                City = p.City,
                PhoneNumber = p.PhoneNumber
            })
            return st.ToList();

after i get the list in another class how can I access each property? 在我获得另一个类的列表后,我如何访问每个属性?

something like 就像是

foreach(object s in St)
{
    string name = s.Name;
}

I have no predefined class to cast the object to it. 我没有预定义的类来将对象强制转换为它。

Can this be done without having to create a class and cast the object to that class type? 这可以在不创建类并将对象强制转换为该类类型的情况下完成吗?

Thanks 谢谢

Are you using C# 4? 你在使用C#4吗? You could try using dynamic : 您可以尝试使用dynamic

foreach(dynamic s in St)
{
    string name = s.Name;
}

The risk is, of course, that if you try to access a property that the object doesn't have you'll only find out at runtime. 当然,风险是,如果您尝试访问该对象没有的属性,您只能在运行时找到它。

As an aside, wouldn't it make more sense in this case to actually create a class that has all these properties? 顺便说一下,在这种情况下,实际创建一个具有所有这些属性的类是不是更有意义? You clearly need them in several places and you'd get the benefits of type-safety and compile-time errors. 您显然需要在几个地方使用它们,并且您将获得类型安全和编译时错误的好处。

You could use the follwing 你可以使用下面的内容

foreach(object s in St)
{
   Type type = s.GetType();
   PropertyInfo property = type.GetProperty("Name");
   if(property !=null)
   {
       string name= (string )property.GetValue(s, null);
   }
}

you have to add the namespace System.Reflection to the class 您必须将命名空间System.Reflection添加到类中

C#3.0具有允许隐式转换的var类型。

The complier is creating you an anonymous type which can be used within the scope of the method. 编译器正在创建一个匿名类型,可以在方法的范围内使用。 If you need to pass the results of LINQ query around then it's best to create a domain object to represent that information like PersonSummary and assign the results of the query to that. 如果你需要传递LINQ查询的结果,那么最好创建一个域对象来表示像PersonSummary这样的信息,并将查询结果分配给它。 C# is strongly typed take advantage of that. C#是强类型的,利用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM