Cast received object to a List<object> or IEnumerable<object>

后端 未结 8 1566
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 23:52

I\'m trying to perform the following cast

private void MyMethod(object myObject)  
{  
    if(myObject is IEnumerable)  
    {
        List c         


        
                      
相关标签:
8条回答
  • 2020-12-08 00:34

    C# 4 will have covariant and contravariant template parameters, but until then you have to do something nongeneric like

    IList collection = (IList)myObject;
    
    0 讨论(0)
  • 2020-12-08 00:37

    You need to type cast using as operator like this.

    private void MyMethod(object myObject)  
    {  
    if(myObject is IEnumerable)  
    {
        List<object> collection = myObject as(List<object>); 
        ... do something   
    }  
    else  
    {  
        ... do something  
    }  
    }      
    
    0 讨论(0)
提交回复
热议问题