C# 获取对象类型并相应地分配值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1110375/
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
get object type and assign values accordingly
提问by Developer
I have an arraylist that gets different type of valuesin it, 1st value->string,2nd value-> datetime, 3rd value--> booleanand 4th value is int, how do I find thier type and assign those values accordingly, any help is appreciated:)
我有一个数组列表,它在其中获取不同类型的值,第一个值->字符串,第二个值->日期时间,第三个值-->布尔值和第四个值是int,我如何找到它们的类型并相应地分配这些值,任何帮助表示赞赏:)
here is my Code:
这是我的代码:
foreach (object obj in lstTop)
{
if(obj.GetType() == string)
{do this...)
else if(obj.GetType() == DateTime)
{do this....}
else if(obj.GetType() == bool)
{do this....}
else if(obj.GetType() == Int)
{do this....}
}
Thank you all, my Final Code:
谢谢大家,我的最终代码:
string Subscription = "";
DateTime issueFirst;
DateTime issueEnd;
foreach (object obj in lstTop)
{
///Type t = obj.GetType();
if (obj is string)
Subscription += obj + ",";
else if (obj is DateTime)
{
Subscription += Convert.ToDateTime(obj).ToShortDateString() + ",";
}
/// else if (t == typeof(DateTime))
}
return ("User Authenticated user name: " + userName + ", Subscription: " + Subscription);
采纳答案by Jamie Ide
foreach (object obj in lstTop)
{
if(obj is string)
{do this.....}
else if(obj is DateTime)
{do this.....}
else if(obj is bool)
{do this.....}
else if(obj is Int)
{do this.....}
else
{
// always have an else in case it falls through
throw new Exception();
}
}
回答by Joel Coehoorn
ArrayLists in .Net 2.0 are almost always the wrong way to do it. Even if you don't know what the list will hold, you're better off using the generic List<Object>
because that communicates to others that the list really could hold anything and isn't just a left over from a .Net 1.1 programmer.
.Net 2.0 中的 ArrayLists 几乎总是错误的做法。即使您不知道列表将包含什么,您最好使用泛型,List<Object>
因为它可以向其他人传达列表确实可以包含任何内容,而不仅仅是 .Net 1.1 程序员的遗留物。
Other than that, the is
keyword should do what you want:
除此之外,is
关键字应该做你想做的:
if (obj is string)
// do this
else if (obj is DateTime)
// do this
// ...
UpdateI know this is old, but it come up in my notices today. Reading it again, it occurs to me that another nice way to do this is via type resolution for an overloaded function:
更新我知道这是旧的,但它今天出现在我的通知中。再读一遍,我发现另一种很好的方法是通过重载函数的类型解析:
void DoSomething(string value) { /* ... */ }
void DoSomething(DateTime value) { /* ... */ }
DoSomething(obj);
回答by John Kugelman
The simplest solution is not to use a loop since you know exactly what's in your list.
最简单的解决方案是不使用循环,因为您确切地知道列表中的内容。
string myString = (string) lstTop[0];
DateTime myDate = (DateTime) lstTop[1];
bool myBool = (bool) lstTop[2];
int myInt = (int) lstTop[3];
回答by Will Eddins
Just some slightly cleaner code:
只是一些稍微干净的代码:
foreach (object obj in lstTop)
{
if(obj is string)
{do this...)
else if(obj is DateTime)
{do this....}
else if(obj is bool)
{do this....}
else if(obj is int)
{do this....}
}
If your array always has the same objects in the same location though, just index into the array and do direct casts.
但是,如果您的数组始终在同一位置具有相同的对象,则只需对数组进行索引并进行直接转换。
回答by Timothy Carter
foreach (object obj in lstTop)
{
if(obj.GetType() == typeof(string))
{do this...)
else if(obj.GetType() == typeof(DateTime))
{do this....}
else if(obj.GetType() == typeof(bool))
{do this....}
else if(obj.GetType() == typeof(int))
{do this....}
}
The GetType
method returns the System.Type
of the object. Therefore you need to compare it with the another System.Type
, which you get by using typeof
.
该GetType
方法返回System.Type
对象的 。因此,您需要将它与System.Type
使用typeof
.
回答by Fredrik M?rk
If your list contains exactly one value of each type you can store it in a Dictionary
instead (if using an ArrayList
is not a specific requirement), and just retrieve the value based on the requested type:
如果您的列表只包含每种类型的一个值,您可以将其存储在 a 中Dictionary
(如果使用 anArrayList
不是特定要求),然后根据请求的类型检索值:
private Dictionary<Type, Object> data = GetDataList();
string myString = (string)data[typeof(string)];
int myInt = (int)data[typeof(int)];
This will make the process of fetching the values slightly more robust since it is not depending on the values appearing in any specific order.
这将使获取值的过程稍微更健壮,因为它不依赖于以任何特定顺序出现的值。
Example of converting the ArrayList to such a dictionary:
将 ArrayList 转换为这样的字典的示例:
ArrayList data = new ArrayList();
data.Add(1);
data.Add("a string");
data.Add(DateTime.Now);
Dictionary<Type, Object> dataDictionary = new Dictionary<Type, object>();
for (int i = 0; i < data.Count; i++)
{
dataDictionary.Add(data[i].GetType(), data[i]);
}
回答by kyoryu
Instead of using primitive types, I'd have an abstract class that encapsulated each data type. Then, the logic of handling that type can be embedded in the class itself.
我没有使用原始类型,而是有一个封装了每种数据类型的抽象类。然后,处理该类型的逻辑可以嵌入到类本身中。
foreach( MyBaseData data in lstData )
{
data.DoTheRightThing();
}
In general, any code that switches on the type of an object should be considered a design smell - it may not necessarily be wrong, but it's probably a good idea to take another look at it.
一般来说,任何切换对象类型的代码都应该被视为一种设计味道——它可能不一定是错误的,但再看一遍可能是个好主意。
While writing a class to encapsulate a simple type may feel like unnecessary work, I don't think I've ever regretted doing it.
虽然编写一个类来封装一个简单的类型可能感觉是不必要的工作,但我认为我从来没有后悔过这样做。