C# wcf从列表继承<;T>;
我正在使用WCF服务,其中对象定义如下:-C# wcf从列表继承<;T>;,c#,wcf,generic-list,C#,Wcf,Generic List,我正在使用WCF服务,其中对象定义如下:- public class Test1 { public string s {get;set;} public string a {get;set;} } public class Test2 { public string u {get;set;} public string v {get;set;} } public class ABC : List<Test1> public class DEF: List<Te
public class Test1
{
public string s {get;set;}
public string a {get;set;}
}
public class Test2
{
public string u {get;set;}
public string v {get;set;}
}
public class ABC : List<Test1>
public class DEF: List<Test2>
public class Test
{
public ABC x {get;set;}
public DEF y {get;set;}
}
上面的代码在运行时向我抛出了一个InvalidCastException。我假设发生这种情况是因为OrderBy返回了一个IORDerenumerable,因此无法强制转换它。我尝试了上述代码的各种变体:-
return (ABC)result.OrderBy(i=>i.s).ThenBy(j=>j.a);
return (ABC)result.OrderBy(i=>i.s).ThenBy(j=>j.a).ToList();
没有一个奏效。
因此,我将测试类更改为:-
public class Test
{
public List<T> x {get;set;}
public List<T> y {get;set;}
}
公共类测试
{
公共列表x{get;set;}
公共列表y{get;set;}
}
所以,现在一切正常。我在某个地方读到,我们不应该在公共API中使用列表。然而,这是否也适用于WCF?而且,这种方法正确吗?还是应该尝试从集合继承ABC和DEF类
我是否应该尝试从集合继承ABC和DEF类
仅当ABC
和DEF
提供的功能高于列表所提供的功能时。即使如此,扩展方法可能更合适
但不清楚为什么会出现InvalidCastException
——您需要添加导致该异常的代码,以了解正确的解决方案 这将导致InvalidCastException
List<Test1> test1 = new List<Test1>();
ABC abc = (ABC)test1;
非常感谢。我会调查的
List<Test1> test1 = new List<Test1>();
ABC abc = (ABC)test1;
List<Test1> test1 = new ABC();
ABC abc = (ABC)test1;
public class ABC : List<Test1>
{
public ABC(IEnumerable<Test1> enumerable)
{
if (enumerable != null)
this.AddRange(enumerable);
}
}
return new ABC(result.OrderBy(i=>i.s).ThenBy(j=>j.a));