[英]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. 我在
Console.WriteLine(item.type)
上收到以下代码,出现CS1061错误,对我来说似乎很简单。
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. 不受约束的泛型只能访问
object
类型上可用的方法或属性。
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. 约束(例如@ Mark-Yisri指定的约束)允许访问与该约束匹配的方法和属性,但随后限制了允许与泛型类型或方法一起使用的类型。
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. 此约束将泛型限制为只能使用LocalDataFolder或从LocalDataFolder继承的类,但是可以访问LocalDataFolder类型的对象中可用的方法和属性。
public class PicturePage<T> where T : LocalDataFolder
Is the item.type
correct? item.type
是否正确? In Java generics cannot have any fields associated with them, you would have to use T extends LocalDataFolder
. 在Java泛型中,不能有任何与之关联的字段,您必须使用
T extends LocalDataFolder
。 Not sure what the relevant syntax is in C#. 不确定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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.