相关疑难解决方法(0)

C#编译器错误?为什么这个隐式的用户定义转换没有编译?

给定以下结构:

public struct Foo<T>
{
   public Foo(T obj) { }

   public static implicit operator Foo<T>(T input)
   {
      return new Foo<T>(input);
   }
}
Run Code Online (Sandbox Code Playgroud)

此代码编译:

private Foo<ICloneable> MakeFoo()
{
    string c = "hello";
    return c; // Success: string is ICloneable, ICloneable implicitly converted to Foo<ICloneable>
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有编译 - 为什么?

private Foo<ICloneable> MakeFoo()
{
    ICloneable c = "hello";
    return c; // Error: ICloneable can't be converted to Foo<ICloneable>. WTH?
}
Run Code Online (Sandbox Code Playgroud)

c# compiler-construction

32
推荐指数
2
解决办法
2634
查看次数

如何将List转换为继承自List <T>的类型?

我有两节课:

public class Row : Dictionary<string,string> {}
public class Table : List<Row> {}
Run Code Online (Sandbox Code Playgroud)

在应该返回Table类型的对象的方法中,我尝试使用Where -Statement过滤Table类型的对象,并在过滤后返回此对象.

Table table = new Table();
table = tableObject.Where(x => x.Value.Equals("")).ToList();
return table;
Run Code Online (Sandbox Code Playgroud)

我的问题是生成的IEnumerable的演员表.

  1. 使用(Table)转换会抛出InvalidCastException

附加信息:无法将'System.Collections.Generic.List`1 [Row]'类型的对象强制转换为'Table'类型.

  1. 使用as转换会导致null对象

如何从IEnumerable中返回Table类型的对象?

c# linq casting

5
推荐指数
1
解决办法
110
查看次数

标签 统计

c# ×2

casting ×1

compiler-construction ×1

linq ×1