How to cast to object type in C #?

I have:

public class MyClass { 
 private string PrivateString; 
}

and I have an interface that accepts:

object o

I have a MyClass list that I need to pass through the o object, and my Google does not give me the opportunity. What is the procedure to make this work? I know this should be insanely simple, but I still need to do type casting in C #.

+3
source share
3 answers
MyClass my = new MyClass ();
WhateverTheFunctionThatTakesObjectIs (my);

Everything will be indirectly applied to the object.

+4
source

List<MyClass> , List object ( ). - , ( , , ), :

myInterfaceFunction((object) myList);

myInterfaceFunction(myList as object);

List<object>, List<MyClass>, :

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

( ToList(), IEnumerable<object> List<object>).

. object - MyFunction(myList) MyFunction(IEnumerable<object> blah) - , MyFunction(object blah).

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 { }
}
+2

You do not need to do type casting to use the MyClass object for a method that takes an object argument, however, you may have problems listing the list of MyClass objects to the list of objects

0
source

Source: https://habr.com/ru/post/1751696/


All Articles