简体   繁体   English

从 C# 中的泛型类返回的列表,但列表(协变)未在主类中更新?

[英]List returned from generic class in c# but list(covariant )is not getting updated in main class?

c# code to return generic List from Class1 c#代码从Class1返回泛型列表

private void Form1_Load(object sender, EventArgs e)
{
Class1<int> obj = new Class1<int>();
List<int> covariant = new List<int>();
covariant = obj.mark();
System.Console.WriteLine(covariant[0]);
}

   public class Class1<T>  
   {
       public List<T> mark()
       {
        List<object> covariant = new List<object>();
        covariant.Add(5);        *unable to get value in covariant list defined. Getting null vlaue*
        return covariant as List<T>;
       }
    }

unable to get value in covariant list defined.无法在定义的协变列表中获取值。 Getting null vlaue unable to get value in covariant list defined.获取空值无法在定义的协变列表中获取值。 Getting null vlaue unable to get value in covariant list defined.获取空值无法在定义的协变列表中获取值。 Getting null vlaue unable to get value in covariant list defined.获取空值无法在定义的协变列表中获取值。 Getting null vlaue获得空值

I think you should not use Generics if you are going to explicitly use int inside your method.我认为如果您要在方法中显式使用int则不应使用Generics

This should be your first hint that you should not use generics in the first place.这应该是您首先不应该使用泛型的第一个hint Here is what your class might look like with a more proper use of generics.这是您的类在更正确地使用泛型后的样子。

public class Class1<T>
    {
        private List<T> covariants = new List<T>();

        public List<T> mark(T item)
        {
            covariants.Add(item);
            return covariants;
        }
    }

var s = new Class1<int>.mark(5) will return a list of count 1. s.mark(10) will return a list with two items. var s = new Class1<int>.mark(5)将返回一个计数为 1 的列表。 s.mark(10)将返回一个包含两个项目的列表。

For more info about c# generics you can read the docs -> https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/有关 c# 泛型的更多信息,您可以阅读文档 -> https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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