Error 7, argument 1: cannot convert from ' 

2019-03-03 12:46发布

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.

3条回答
贪生不怕死
2楼-- · 2019-03-03 13:11

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.

查看更多
别忘想泡老子
3楼-- · 2019-03-03 13:26

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);
查看更多
Melony?
4楼-- · 2019-03-03 13:34

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.

查看更多
登录 后发表回答