开发者

How do I do a cast to an object type in C#?

I have a:

public class MyClass { 
 private string PrivateString; 
}

and I have an interface that accepts:

object o

I have a开发者_StackOverflow中文版 list of MyClass that I need to push through object o, and my Google is failing me. What's the procedure to make this work? I know this must be crazy simple, but I've yet to do type casting in C#.


MyClass my = new MyClass();
WhateverTheFunctionThatTakesObjectIs(my);

Everything will implicitly cast to object.


The List<MyClass> object can still be just passed to your interface implementation, because List can be implicitly cast down to object (as can all objects). If the compiler complains because of the way you have your code set up (i have to say that because you haven't actually shown us any code) then you can explicitly cast it:

myInterfaceFunction((object) myList);

or:

myInterfaceFunction(myList as object);

If you want to cast the contents of the list and pass a List<object> when you already have a List<MyClass> then you can just do this:

myInterfaceFunction(myList.Cast<object>().ToList());

(you can get rid of the ToList() if your interface function uses IEnumerable<object> instead of List<object>).

Here is a quick example. This has a good illustration of my comment about explicitly casting to object - by default the call to MyFunction(myList) will go to the MyFunction(IEnumerable<object> blah) function - you have to explicitly cast it to force it to go to the MyFunction(object blah) function.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<MyObject> myList = new List<MyObject>();

            MyFunction(myList);
            MyFunction((object)myList);
            MyFunction(myList.Cast<object>().ToList());
            MyFunction(myList.Cast<object>());
        }


        public static void MyFunction(List<object> blah)
        {
            Console.WriteLine(blah.GetType().ToString());
        }

        public static void MyFunction(IEnumerable<object> blah)
        {
            Console.WriteLine(blah.GetType().ToString());
        }

        public static void MyFunction(object blah) 
        {
            Console.WriteLine(blah.GetType().ToString());
        }
    }


    public class MyObject { }
}


You don't needed to do any type casting to use a MyClass object for a method taking an object argument however you might have problems casting a list of MyClass objects to a list of objects

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜