相关疑难解决方法(0)

令人费解的Enumerable.Cast InvalidCastException

以下抛出一个InvalidCastException.

IEnumerable<int> list = new List<int>() { 1 };
IEnumerable<long> castedList = list.Cast<long>();
Console.WriteLine(castedList.First());
Run Code Online (Sandbox Code Playgroud)

为什么?

我正在使用Visual Studio 2008 SP1.

.net c# exception

44
推荐指数
2
解决办法
7629
查看次数

Enumerable.Cast <T>扩展方法无法从int转换为long,为什么?

可能重复:
令人困惑的Enumerable.Cast InvalidCastException

嗨,

我只是注意到Enumerable.Cast<T>扩展方法有些奇怪......似乎它无法转换intlong,即使这个演员是完全合法的.

以下代码失败InvalidCastException:

        foreach (var item in Enumerable.Range(0,10).Cast<long>())
        {
            Console.WriteLine(item);
        }
Run Code Online (Sandbox Code Playgroud)

但是这个代码,我认为是相同的,确实有效:

        foreach (var item in Enumerable.Range(0,10).Select(i => (long)i))
        {
            Console.WriteLine(item);
        }
Run Code Online (Sandbox Code Playgroud)

谁能解释这种行为?我用Reflector查看了Cast方法的代码,但是Reflector无法解释迭代器块,所以很难理解......

c# linq casting

17
推荐指数
2
解决办法
7058
查看次数

将IEnumerable <T>转换为IEnumerable <U>?

以下符合但在运行时抛出异常.我想要做的是将类PersonWithAge强制转换为Person类.我该怎么做,有什么工作?

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class PersonWithAge
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<PersonWithAge> pwa = new List<PersonWithAge>
        {
            new PersonWithAge {Id = 1, Name = "name1", Age = 23},
            new PersonWithAge {Id = 2, Name = "name2", Age = 32} …
Run Code Online (Sandbox Code Playgroud)

c# ienumerable casting

12
推荐指数
3
解决办法
2万
查看次数

如何在C#中控制类型转换

有没有办法控制C#中的类型转换?例如,如果我有两种类型具有基本相同的细节,但一种用于我的应用程序的内部工作,另一种是用于与非.Net应用程序通信的DTO:

public sealed class Player
{
  public Player(string name, long score)
  {
    Name = name;
    Score = score;
    ID = Guid.NewGuid();
  }

  public string Name { get; private set; }

  public Guid ID { get; private set; }

  public long Score { get; private set; }
}

public sealed class PlayerDTO
{
  public PlayerDTO(string name, long score, string id)
  {
    Name = name;
    Score = score;
    ID = id;
  }

  public string Name { get; private set; }

  // the …
Run Code Online (Sandbox Code Playgroud)

.net c# types type-conversion

7
推荐指数
2
解决办法
1007
查看次数

标签 统计

c# ×4

.net ×2

casting ×2

exception ×1

ienumerable ×1

linq ×1

type-conversion ×1

types ×1