[英]C# typeof(“Object Variable get type”)
I have a class that has a property of type object that will get the value of an Entity Framework table. 我有一个具有类型为object的属性的类,该属性将获取实体框架表的值。
Here is the properties of the class: 这是该类的属性:
public string EntityName
{
get { return _entityName; }
set { _entityName = value; }
}
private string _entityName;
public object EntityType
{
get { return _entityType; }
set { _entityType = value; }
}
private object _entityType;
The object can be any table, depends on when it was initialized. 该对象可以是任何表,取决于它何时初始化。 Next I want all the column names of the table in the object.
接下来,我想要对象中表的所有列名称。 Here is the code that should give it to me:
这是应该给我的代码:
public ObservableCollection<string> ReadColumnNames()
{
IEnumerable<string> names = typeof("Problem Here").GetProperties()
.Select(property => property.Name)
.ToList();
ObservableCollection<string> observableNames = new ObservableCollection<string>();
foreach (string name in names)
{
observableNames.Add(name);
}
return observableNames;
}
Problem is that the typeof() method requires a type and the type can be of any table. 问题是typeof()方法需要一个类型,并且该类型可以是任何表。 If I create a variable of Type ie Type myType = EntityDetail.GetType() the typeof() denies it because it is a variable and not a type.
如果我创建类型的变量,即类型myType = EntityDetail.GetType(),则typeof()会拒绝它,因为它是变量而不是类型。
Any suggestions on what I can do? 有什么建议我可以做什么?
I don't know if there is a better way to do this, if there is feel free to share. 我不知道是否有更好的方法可以共享。
Thanks in advance. 提前致谢。
This maybe? 这也许吗?
IEnumerable<string> names = typeof(EntityDetail).GetProperties()
.Select(property => property.Name)
.ToList();
Note that this requires a using System.Linq
. 请注意,这需要
using System.Linq
。
typeof
will expect a compile -time type. typeof
将需要一个编译时类型。 If you don´t know the actuaö type at compile-time, use myInstance.GetType()
instead of typeof(...)
instead. 如果在编译时不知道actuaö类型,请使用
myInstance.GetType()
而不是typeof(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.