[英]C# typeof(“Object Variable get type”)
我有一个具有类型为object的属性的类,该属性将获取实体框架表的值。
这是该类的属性:
public string EntityName
{
get { return _entityName; }
set { _entityName = value; }
}
private string _entityName;
public object EntityType
{
get { return _entityType; }
set { _entityType = value; }
}
private object _entityType;
该对象可以是任何表,取决于它何时初始化。 接下来,我想要对象中表的所有列名称。 这是应该给我的代码:
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;
}
问题是typeof()方法需要一个类型,并且该类型可以是任何表。 如果我创建类型的变量,即类型myType = EntityDetail.GetType(),则typeof()会拒绝它,因为它是变量而不是类型。
有什么建议我可以做什么?
我不知道是否有更好的方法可以共享。
提前致谢。
这也许吗?
IEnumerable<string> names = typeof(EntityDetail).GetProperties()
.Select(property => property.Name)
.ToList();
请注意,这需要using System.Linq
。
typeof
将需要一个编译时类型。 如果在编译时不知道actuaö类型,请使用myInstance.GetType()
而不是typeof(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.