Error 7, argument 1: cannot convert from ' ' to ' ' [duplicate]

ぃ、小莉子 提交于 2019-12-02 16:57:53

问题


I am coming across an error that I have not seen before. I am hoping some one can help.

Here is my code:

public class MyT
{
    public int ID { get; set; }
    public MyT Set(string Line)
    {
        int x = 0;

        this.ID = Convert.ToInt32(Line);

        return this;
    }
}

public class MyList<T> : List<T> where T : MyT, new()
{
    internal T Add(T n)
    {
        Read();
        Add(n);
        return n;
    }
    internal MyList<T> Read()
    {
        Clear();
        StreamReader sr = new StreamReader(@"../../Files/" + GetType().Name + ".txt");
        while (!sr.EndOfStream)
            Add(new T().Set(sr.ReadLine())); //<----Here is my error!
        sr.Close();
        return this;
    }
}

public class Customer : MyT
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Item : MyT
{
    public int ID { get; set; }
    public string Category { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }
}

public class MyClass
{
    MyList<Customer> Customers = new MyList<Customer>();
    MyList<Item> Items = new MyList<Item>();
}

On the line that says, "Add(new T().Set(sr.ReadLine()));" I get "Error 7, Argument 1: cannot convert from 'Simple_Reservation_System.MyT' to 'T'". Can someone please help me fix this.


回答1:


Your type MyList can only contain elements of type "T" (specified when the list is declared). The element you are trying to add is of type "MyT", which cannot be downcasted to "T".

Consider the case in which MyList is declared with another subtype of MyT, MyOtherT. It is not possible to cast MyT to MyOtherT.




回答2:


Because your type MyT is not the same that generic parameter T. When you write this new T() you create an instance of type T that must be inherited from MyT, but this is not necessarily the type of MyT. Look at this example to see what I mean:

public class MyT1 : MyT
{

}
//You list can contains only type of MyT1
var myList = new MyList<MyT1>();

var myT1 = new MyT1();
//And you try to add the type MyT to this list.
MyT myT = myT1.Set("someValue");
//And here you get the error, because MyT is not the same that MyT1.
myList.Add(myT);



回答3:


Your Add parameter takes the generic type T. Your Set method return a concrete class MyT. It is not equal to T. In fact even if you call this:

Add(new MyT())

it will return an error.

I would also like to add that this is an error only while you are inside the MyList class. If you call the same method from a different class it will work.



来源:https://stackoverflow.com/questions/16477176/error-7-argument-1-cannot-convert-from-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!