C# 将对象转换为通用列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/694154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast an object into generic list
提问by Amit Sharma
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.
将 object 转换为 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
问候阿米特
采纳答案by Dave
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 声明为泛型类型参数,那么我可以在该语句中看到的唯一编译时问题是使用关键字object
作为变量名。无论如何,我建议这样的事情最能表达您的意图:
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null)
{
foreach (object item in enumerable)
{
sTemp += item.ToString();
}
}
You may also want to consider using a StringBuilderif your list is likely to have a lot of items.
如果您的列表可能有很多项目,您可能还需要考虑使用StringBuilder。
回答by Charlie Flowers
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”关键字验证“object”实际上是“is-a”List<T>。如果是这样,你会从中得到一个 List< T > 。如果没有,您将获得空值。
回答by Brijesh Mishra
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 是对象
回答by MarcE
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
}
回答by Khanh Hua
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;
}
}