简体   繁体   中英

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.

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. 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.

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 .

typeof will expect a compile -time type. If you don´t know the actuaö type at compile-time, use myInstance.GetType() instead of typeof(...) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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