简体   繁体   English

将对象转换为通用列表

[英]Cast an object into generic list

I have a requirement where I can get the following in an object - 我有一个要求,我可以在一个对象中获得以下内容 -

a type T or List<T> 

Converting object into T is easy. 将对象转换为T很容易。 How can I convert it to List(by first checking that it can be converted successfully or not), reason I want to convert is to scroll through the list and call tostring on each element. 如何将其转换为List(通过首先检查它是否可以成功转换),我想转换的原因是滚动列表并在每个元素上调用tostring。

My actual code - 我的实际代码 -

namespace Generic_Collection_Code
{
    class Program
    {
        public static string DumpObj(object obj)
        {
            string sTemp = String.Empty;

            List<int> ints = obj as List<int>;
            if (ints != null)
            {
                foreach (int i in ints)
                    sTemp += i.ToString() + ",";
                sTemp.Trim(',');
            }
            else 
            {
                List<string> strings = obj as List<string>;
                if (strings != null)
                {
                    foreach (string s in strings)
                        sTemp += s + ",";
                    sTemp.Trim(',');
                }
                else
                {
                    sTemp += obj.ToString();
                }
            }
            return sTemp;
        }
        static void Main(string[] args)
        {
            List<int> listInts = new List<int>();
            listInts.Add(1);
            listInts.Add(2);
            listInts.Add(3);

            Console.WriteLine("Object1: {0}", DumpObj(listInts));
            int i = 90;

            Console.WriteLine("Object2 {0}", DumpObj(i));


            List<string> listStrings = new List<string>();
            listStrings.Add("1");
            listStrings.Add("2");
            listStrings.Add("3");

            Console.WriteLine("Object3: {0}", DumpObj(listStrings));
            Console.ReadKey();
        }
    }
}

The above code works but I know its an ugly way to achieve this. 上面的代码有效,但我知道这是一种难以实现的方法。 I wanted to ask from community how can I have this function like - 我想从社区问我怎么能有这样的功能 -

    public static string DumpObj<T>(object obj)
    {
        string sTemp = String.Empty;

        List<T> list = obj as List<T>;
        if (list != null)
        {
            foreach (T i in list)
                sTemp += i.ToString() + ",";
            sTemp.Trim(',');
        }
        return sTemp;
    }

This gives me compilation errors as I have to specify T while calling DumpObj with error as - 这给了我编译错误,因为我必须在调用DumpObj时指定T,错误为 -

Error 1 The type arguments for method 'Generic_Collection_Code.Program.DumpObj(object)' cannot be inferred from the usage. 错误1无法从用法中推断出方法'Generic_Collection_Code.Program.DumpObj(object)'的类型参数。 Try specifying the type arguments explicitly. 尝试显式指定类型参数。 D:\\DotNet\\Generic_Collection_Code\\Generic_Collection_Code\\Program.cs 57 47 Generic_Collection_Code D:\\ DotNet \\ Generic_Collection_Code \\ Generic_Collection_Code \\ Program.cs 57 47 Generic_Collection_Code

as you can see, obj is an object, i dont know its type while calling dumobj. 正如你所看到的,obj是一个对象,我在调用dumobj时不知道它的类型。

I hope I have made myself clear on this one. 我希望我已经明确表达了这一点。

I appreciate your time! 我感谢你的时间!

Regards Amit 关心阿米特

Say

List<T> genericList = object as List<T>;

if(genericList != null)
{
   // Do the loop
}

The "as" keyword verifies that "object" actually "is-a" List< T >. “as”关键字验证“对象”实际上是“is-a”List <T>。 If so, you get a List< T > back from it. 如果是这样,您将从中获得List <T>。 If not, you get null. 如果没有,你会得到null。

What is the compilation error you're getting? 你得到的编译错误是什么? If T is declared as a generic type parameter in your context then then the only compile-time issue I can see with that statement is the use of the keyword object as a variable name. 如果在上下文中将T声明为泛型类型参数,那么我可以在该语句中看到的唯一编译时问题是使用关键字object作为变量名。 At any rate, I'd suggest something like this as best expressing your intention: 无论如何,我建议这样做最能表达你的意图:

IEnumerable enumerable = obj as IEnumerable;

if (enumerable != null)
{
    foreach (object item in enumerable)
    {
        sTemp += item.ToString();
    }
}

You may also want to consider using a StringBuilder if your list is likely to have a lot of items. 如果您的列表可能包含大量项目,您可能还需要考虑使用StringBuilder

you cant do this 你不能这样做

List<T> genericList = (List<T>)object

might be you want 可能你想要的

List<T> genericList = (List<T>)obj

where obj is object obj是对象

How about casting the Object into System.Collections.IList (instead of the Generic version) because Generic list also implement this interface. 如何将Object转换为System.Collections.IList(而不是Generic版本),因为Generic list也实现了这个接口。 Then cast each of them into the desired type. 然后将它们中的每一个投射成所需的类型。 Here is what I am working on.. 这是我正在做的工作..

private static void DataSourcePropertyChanged(DependencyObject sender,     
        DependencyPropertyChangedEventArgs args) {
        BarChart _ = sender as BarChart;

        if (args.Property.Equals(BarChart.DataSourceProperty)) {
            System.Collections.IList data = (System.Collections.IList)args.NewValue;
            if (data == null) return;

            foreach (object __ in data) {
                IChartDataItem item = __ as IChartDataItem;
                BarChartItem bar = new BarChartItem() {
                    Label = item.Label,
                    Value = item.Value
                };
                _._visualCollection.Add(bar);

                if (_.MaxData < item.Value)
                    _.MaxData = item.Value;
            }

            if (_.Orientation == Orientation.Horizontal)
                _.Ratio = _.Width / _.MaxData;
        }
    }

How about combining "as" with "is"? 将“as”与“is”结合起来怎么样?

if (object is List<T>)
{ 
  List<T> genericlist = object as List<T>;
 // loop list
}
else if (object is T)
{
 // do something else
}

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

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