将对象转换为通用列表

时间:2022-09-11 10:35:48

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. 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.

将对象转换为T很容易。如何将其转换为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. Try specifying the type arguments explicitly. D:\DotNet\Generic_Collection_Code\Generic_Collection_Code\Program.cs 57 47 Generic_Collection_Code

错误1无法从用法推断出方法'Generic_Collection_Code.Program.DumpObj(object)'的类型参数。尝试显式指定类型参数。 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

5 个解决方案

#1


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. At any rate, I'd suggest something like this as best expressing your intention:

你得到的编译错误是什么?如果在上下文中将T声明为泛型类型参数,那么我可以在该语句中看到的唯一编译时问题是使用关键字对象作为变量名。无论如何,我建议这样做最能表达你的意图:

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。

#2


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 >. If so, you get a List< T > back from it. If not, you get null.

“as”关键字验证“对象”实际上是“is-a”List 。如果是这样,您将从中获得List 。如果没有,你会得到null。

#3


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是对象

#4


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
}

#5


How about casting the Object into System.Collections.IList (instead of the Generic version) because Generic list also implement this interface. Then cast each of them into the desired type. Here is what I am working on..

如何将Object转换为System.Collections.IList(而不是Generic版本),因为Generic list也实现了这个接口。然后将它们中的每一个投射成所需的类型。这是我正在做的工作..

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;
        }
    }

#1


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. At any rate, I'd suggest something like this as best expressing your intention:

你得到的编译错误是什么?如果在上下文中将T声明为泛型类型参数,那么我可以在该语句中看到的唯一编译时问题是使用关键字对象作为变量名。无论如何,我建议这样做最能表达你的意图:

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。

#2


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 >. If so, you get a List< T > back from it. If not, you get null.

“as”关键字验证“对象”实际上是“is-a”List 。如果是这样,您将从中获得List 。如果没有,你会得到null。

#3


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是对象

#4


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
}

#5


How about casting the Object into System.Collections.IList (instead of the Generic version) because Generic list also implement this interface. Then cast each of them into the desired type. Here is what I am working on..

如何将Object转换为System.Collections.IList(而不是Generic版本),因为Generic list也实现了这个接口。然后将它们中的每一个投射成所需的类型。这是我正在做的工作..

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;
        }
    }