简体   繁体   中英

How do I access a variable in a generic class

I'm getting a CS1061 error on with following code at Console.WriteLine(item.type) which seems simple enough to me.

Can anyone help me here please?

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            LocalPage lp = new LocalPage();
            lp.Put();
        }
    }
    public class LocalDataFolder
    {
        public LocalDataFolder() { }
        public int type;
    }
    public class PicturePage<T>
    {
        public List<T> folders = new List<T>() { };
        public void Put()
        {
            foreach (T item in folders)
                Console.WriteLine(item.type); 
        }
    }
    public class LocalPage : PicturePage<LocalDataFolder>
    {
        public LocalPage()
        {
            folders.Add(new LocalDataFolder());
        }
    }
}

An unconstrained generic can only access methods or properties available on the object type.

A constraint, such as the one specified by @Mark-Yisri, enables access to methods and properties matching the constraint, but then limits the types allowed to be used with the generic type or method.

This constraint restricts the generic to working with LocalDataFolder or classes that inherit from LocalDataFolder, but enables access to methods and properties available in an object of type LocalDataFolder.

public class PicturePage<T> where T : LocalDataFolder

Is the item.type correct? In Java generics cannot have any fields associated with them, you would have to use T extends LocalDataFolder . Not sure what the relevant syntax is in C#.

Try this:

public class PicturePage<T> where T : LocalDataFolder
{
    public List<T> folders = new List<T>() { };
    public void Put()
    {
        foreach (T item in folders)
            Console.WriteLine(item.type); 
    }
}

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