C# 错误7,参数1:无法从'';至'';
我遇到了一个以前从未见过的错误。我希望有人能帮忙 这是我的密码:C# 错误7,参数1:无法从'';至'';,c#,list,customization,type-conversion,C#,List,Customization,Type Conversion,我遇到了一个以前从未见过的错误。我希望有人能帮忙 这是我的密码: 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&
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>();
}
公共类MyT
{
公共int ID{get;set;}
公共MyT集(字符串行)
{
int x=0;
this.ID=Convert.ToInt32(行);
归还这个;
}
}
公共类MyList:列表,其中T:MyT,new()
{
内部T添加(T n)
{
Read();
添加(n);
返回n;
}
内部MyList Read()
{
清除();
StreamReader sr=新的StreamReader(@./../Files/“+GetType().Name+.txt”);
而(!sr.EndOfStream)
Add(new T().Set(sr.ReadLine());//您的类型MyList只能包含类型为“T”的元素(在声明列表时指定)。您尝试添加的元素类型为“MyT”,不能向下转换为“T”
考虑使用MyT的另一个子类型MyOtherT声明MyList的情况。无法将MyT强制转换为MyOtherT。您的Add参数采用泛型类型T。您的Set方法返回一个具体类MyT。它不等于T。事实上,即使您调用它:
添加(新的MyT())
它将返回一个错误
我还想补充一点,只有当您在MyList类中时,这才是一个错误。如果您从不同的类调用相同的方法,它将起作用。因为您的类型MyT
与泛型参数T
不同。编写此new T()
您创建了类型为T
的实例,该实例必须继承自MyT
,但这不一定是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);
公共类MyT1:MyT
{
}
//您的列表只能包含MyT1的类型
var myList=new myList();
var myT1=新的myT1();
//然后尝试将类型MyT添加到此列表中。
MyT MyT=myT1.Set(“someValue”);
//这里是错误,因为MyT和MyT1不一样。
myList.Add(myT);
坦率地说,这不是很“通用”,为什么不在MyList中使用List?简短版本:您正试图将MyT
对象放入一个列表中,根据您的构造函数,该列表可能需要包含MyT
的任意子类。请参阅标记的duplicate以了解为什么这是危险的和不允许的。如果没有关于你的问题有更多的细节。但实际上,你应该研究这个问题,然后自己决定你到底想发生什么。好的。那么我该如何解决它呢?我不知道你任务的细节。例如,你可以从列表
继承你的MyList
类,然后你的类将不是泛型的。但它将是泛型的如果您创建一个类来负责读取文件并返回List
的一个实例,那就更好了。您能给我一个例子吗?您的代码中有一个例子:类Customer派生自MyT。为了说明错误:在有问题的行中,您将尝试将类型为“MyT”的对象强制转换为类型为“Customer”这是不允许的。您可以始终强制转换为超类型,但决不能转换为子类型。我明白了。现在我如何修复它?与其将Set函数与其显式返回类型一起使用,不如将该逻辑放入类型的构造函数中。您的文件读取可能会有所不同,这取决于您是在读取客户还是项目。