相关疑难解决方法(0)

144
推荐指数
5
解决办法
3万
查看次数

Linq - 为IList转换IQueryable返回null - 为什么?

我必须在这里遗漏一些明显的东西.我不明白为什么这个linq查询结果的转换返回null而不是我正在请求的类型列表.

IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>;
Run Code Online (Sandbox Code Playgroud)

运行它的完整代码如下.这是我需要弥合的知识差距.我已经尝试过各种各样的演员阵容来让它发挥作用.我没有异常,只是一个空.值得注意的是,Linq查询将其结果选择为我的自定义"MyDataClass"的实例,该实现IMyDataInterface

class Program
{
    static void Main(string[] args)
    {
        IMyFunctionalInterface myObject = new MyClass();


        //myObject.Get() returns null for some reason...
        IList<IMyDataInterface> list = myObject.Get();

        Debug.Assert(list != null, "Cast List is null");
    }
}

public interface IMyFunctionalInterface
{
    IList<IMyDataInterface> Get();
}

public class MyClass : IMyFunctionalInterface
{
    public IList<IMyDataInterface> Get()
    {
        string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };

        var query = from n in names
                    where n.Contains("a")
                    select new MyDataClass
                    { …
Run Code Online (Sandbox Code Playgroud)

linq generics interface

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

C#:泛型的语义?

我有一个清单:

private readonly IList<IList<GameObjectController>> removeTargets;
private readonly IList<IList<GameObjectController>> addTargets;
Run Code Online (Sandbox Code Playgroud)

PickUp继承自GameObjectController.但是,当我尝试这个:

public IList<PickUp> Inventory

// ... 

gameObjectManager.MoveFromListToWorld(this, user.Model.Inventory);

// ...

    // This queues everything up to be removed, until ProcessMoves...() is called
    public void MoveFromWorldToList(GameObjectController removedFromWorld, IList<GameObjectController> addTarget)
    {
        toBeRemoved.Add(removedFromWorld);
        addTargets.Add(addTarget);
    }

// ...

    /// <summary>
    /// Removes all the GameObjects on which removal is requested from the world.
    /// </summary>
    public void ProcessMovesFromListToWorld()
    {
        for (int i = 0; i < toBeAdded.Count; i++)
        {
            GameObjectController moved = …
Run Code Online (Sandbox Code Playgroud)

c# generics semantics

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

标签 统计

c# ×2

generics ×2

c#-4.0 ×1

contravariance ×1

covariance ×1

interface ×1

linq ×1

semantics ×1