简体   繁体   中英

Passing class as parameter in C# and then wanting to access property of class

I'm trying to refactor some code as I have about 7 occurrences of code like this:

List<RHEvent> eventResults = DBConnection.Table<RHEvent>().Where(t => (int)t.PreferredImage == ID).ToList();
foreach (RHEvent result in eventResults)
{
    result.PreferredImage = 0;
    DBConnection.Update(result);
}

where RHEvent changes to different class names through the different occurrences.

I've started to try and write more generalised code but I'm hitting a snag. Here is what I've got so far:

private void ResetPreferredImage<T>(int ID) where T: new()
{
    List<T> results = DBConnection.Table<T>().Where(t => (int)t.PreferredImage == ID).ToList();
}

The problem is that the compiler doesn't like PreferredImage because it cannot identify it in the abstract class.

Is there a way to reassure the compiler that the property exists or is it simply not possible to do what I'm trying to do?

Thanks.

Philip

you can try something like this

private void ResetPreferredImage<T>(int ID) where T : BaseClass,new()
        {
            List<T> results = DBConnection.Table<T>().Where(t => (int)t.PreferredImage == ID).ToList(); 
        }

Now the Compiler will recognize the PreferredImage Property as a property of a base class

If they do not implement a base class which exposes a PrefferedImage property, your only other option would be to use reflector.

See C# Reflection and Getting Properties

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