【问题标题】:Error 7, argument 1: cannot convert from ' ' to ' ' [duplicate]错误 7,参数 1:无法从“”转换为“”[重复]
【发布时间】:2013-05-10 07:23:17
【问题描述】:

我遇到了一个我以前从未见过的错误。我希望有人可以提供帮助。

这是我的代码:

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>();
}

在写着“Add(new T().Set(sr.ReadLine()));”的那一行我收到“错误 7,参数 1:无法从 'Simple_Reservation_System.MyT' 转换为 'T'”。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 坦率地说,这不是很“通用”,你为什么不在 MyList 中使用 List 呢?
  • 简短版:您正试图将MyT 对象放入一个列表中,根据您的约束,该列表可能需要包含MyT 的任意子类。请参阅标记的重复项,了解为什么这是危险的和不允许的。如果没有更多关于您的问题的详细信息,则无法知道解决它的适当方法是什么。但实际上,您应该研究问题并自己决定您真正想要发生的事情。

标签: c# list customization type-conversion


【解决方案1】:

您的 MyList 类型只能包含“T”类型的元素(在声明列表时指定)。您尝试添加的元素是“MyT”类型,不能向下转换为“T”。

考虑使用 MyT 的另一个子类型 MyOtherT 声明 MyList 的情况。无法将 MyT 转换为 MyOtherT。

【讨论】:

  • 你能举个例子吗?
  • 您的代码中有一个示例:类 Customer 派生自 MyT。因此,为了说明错误:在有问题的行上,您将尝试将类型“MyT”的对象转换为类型“客户”,这是不允许的。您始终可以转换为超类型,但不能转换为子类型。
  • 我明白了。现在我该如何解决?
  • 您应该将该逻辑放入该类型的构造函数中,而不是使用具有显式返回类型的 Set 函数。无论如何,您的文件读取可能会有所不同,具体取决于您读取的是客户还是商品。
【解决方案2】:

因为您的类型MyT 与泛型参数T 不同。当您编写此new T() 时,您创建了一个必须从MyT 继承的T 类型的实例,但这不一定是MyT 的类型。看看这个例子,明白我的意思:

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);

【讨论】:

  • 好的。那么我该如何解决呢?
  • 我不知道你的任务细节。例如,您可以从List&lt;MyT&gt; 继承您的MyList 类,然后您的类将不是通用的。但是如果你创建一个类来负责读取文件并返回一个List &lt;MyT&gt;的实例会更好。
【解决方案3】:

您的 Add 参数采用泛型类型 T。您的 Set 方法返回一个具体的类 MyT。不等于T。其实就算你这样称呼:

添加(new MyT())

它会返回一个错误。

我还想补充一点,只有当您在 MyList 类中时,这才是一个错误。如果你从不同的类调用相同的方法,它会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2020-09-08
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多