获取对象类型并相应地分配值

发布于 2024-07-26 10:39:47 字数 1251 浏览 3 评论 0原文

我有一个数组列表,其中包含不同类型的值,第一个值->字符串,第二个值-> 日期时间,第三个值--> boolean 和第四个值是int,我如何找到他们的类型并相应地分配这些值,任何帮助表示赞赏:)

这是我的代码: >

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

谢谢大家,我的最终代码:

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

I have an arraylist that gets different type of values in it, 1st value->string,2nd value-> datetime, 3rd value--> boolean and 4th value is int, how do I find thier type and assign those values accordingly, any help is appreciated:)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦巷 2024-08-02 10:39:47
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();
          }
        }
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();
          }
        }
带刺的爱情 2024-08-02 10:39:47

.Net 2.0 中的 ArrayList 几乎总是错误的方法。 即使您不知道列表将保存什么,您最好使用通用的 List因为这会告诉其他人该列表确实可以保存任何内容,而不仅仅是一个.Net 1.1 程序员留下的。

除此之外,is 关键字应该执行您想要的操作:

if (obj is string)
    // do this
else if (obj is DateTime)
    // do this
// ...

更新 我知道这是旧的,但它出现在我今天的通知中。 再次阅读它,我发现另一种很好的方法是通过重载函数的类型解析:

void DoSomething(string value) { /* ... */ }
void DoSomething(DateTime value) { /* ... */ }

DoSomething(obj);

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.

Other than that, the is keyword should do what you want:

if (obj is string)
    // do this
else if (obj is DateTime)
    // do this
// ...

Update I 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);
但可醉心 2024-08-02 10:39:47

最简单的解决方案是不使用循环,因为您确切知道列表中的内容。

string   myString = (string)   lstTop[0];
DateTime myDate   = (DateTime) lstTop[1];
bool     myBool   = (bool)     lstTop[2];
int      myInt    = (int)      lstTop[3];

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];
王权女流氓 2024-08-02 10:39:47

如果您的列表恰好包含每种类型的一个值,您可以将其存储在 Dictionary 中(如果使用 ArrayList 不是特定要求),并且只需根据关于请求的类型:

private Dictionary<Type, Object> data = GetDataList();
string myString = (string)data[typeof(string)];
int myInt = (int)data[typeof(int)];

这将使获取值的过程稍微更加稳健,因为它不依赖于以任何特定顺序出现的值。

将 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]);
}

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:

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 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]);
}
孤云独去闲 2024-08-02 10:39:47

我不使用原始类型,而是使用一个封装每种数据类型的抽象类。 然后,处理该类型的逻辑可以嵌入到类本身中。

foreach( MyBaseData data in lstData )
{
    data.DoTheRightThing();
}

一般来说,任何打开对象类型的代码都应该被视为设计味道 - 它可能不一定是错误的,但重新审视它可能是个好主意。

虽然编写一个类来封装简单类型可能感觉像是不必要的工作,但我认为我从来没有后悔这样做。

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.

权谋诡计 2024-08-02 10:39:47

只是一些稍微简洁的代码:

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

如果您的数组始终在同一位置具有相同的对象,则只需索引到数组并进行直接转换。

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.

瘫痪情歌 2024-08-02 10:39:47
        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....}
        }

GetType 方法返回对象的System.Type。 因此,您需要将其与通过使用 typeof 获得的另一个 System.Type 进行比较。

        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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文