简体   繁体   English

将动态对象转换为IEnumerable Issue

[英]Convert dynamic object to IEnumerable Issue

protected override IEnumerable<dynamic> GetData()
{
    var request = new RestRequest();
    var directoryResponse = client.ExecuteTaskAsync(request).Result;

    dynamic directory = JsonConvert.DeserializeObject<MyDTO>(directoryResponse.Content);

    cachedDirectory = directory;
}

return cachedDirectory;

Issue is on the line 问题就在网上

cachedDirectory = directory;

Whenever it tries convert the dynamic object to an IEnumerable type. 每当尝试将dynamic对象转换为IEnumerable类型。

Exception message: 异常消息:

Cannot implicitly convert type 'MyDTO' to 'System.Collections.Generic.IEnumerable<object>'. 无法将类型'MyDTO'隐式转换为'System.Collections.Generic.IEnumerable <object>'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)

I have to make few assumption. 我不必做任何假设。

  • I assume that your cachedDirectory object is type of IEnumerable. 我假设您的cachedDirectory对象是IEnumerable类型。 If this is the case then it is clear that it can not convert MyDTO object to IEnumerable at runtime and it throw exception. 如果是这种情况,那么很明显它无法在运行时将MyDTO对象转换为IEnumerable,并且会引发异常。

Following code give you error. 以下代码给您错误。 I assume that you need enumrable. 我认为您需要枚举。

    public class NewTest
    {
        IEnumerable<dynamic> cachedDirectory;
        public IEnumerable<dynamic> GetData()
        {
            dynamic directory = JsonConvert.DeserializeObject<MyDTO>("{ 'Name' : 'Test'  }");
            cachedDirectory = directory;
            return cachedDirectory;            
        }
    }

    public class MyDTO
    {
        public string Name { get; set; }
    }

// This is how you call. //这就是您的呼叫方式。 (This code give error) (此代码给出错误)

    NewTest test = new NewTest();
    IEnumerable<dynamic> result = test.GetData();

Answer : If above is the way you use then you can do something like this. 答案:如果使用上述方法,则可以执行以下操作。

public class NewTest
{
    IEnumerable<dynamic> cachedDirectory;
    public IEnumerable<dynamic> GetData()
    {
         var request = new RestRequest();
        var directoryResponse = client.ExecuteTaskAsync(request).Result;
        dynamic directory = JsonConvert.DeserializeObject<IEumerable<MyDTO>>(directoryResponse.Content);            
        return directory;            
    }
}

public class MyDTO
{
    public string Name { get; set; }
}

// Now this will work. //现在可以使用。

    NewTest test = new NewTest();
    IEnumerable<dynamic> result = test.GetData();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM