1

my method look something like:

Boolean actions(List<Object> input)
{
    if (input.element is String)
    {...}
    else if (input.element is PSObject)
    {...}
}

I tried input.getType().GetGenericArguments()[0] == new PSObject().GetType())

but input.getType().GetGenericArguments()[0] says it is object type...


Check whether the app.config file exists or not in console app C#

I create a console app in C#. I want to use an app.config file in my project.

My problem is: before reading from app.config, I want to make sure that the app.config exists. How to check it?

Please help me! Thanks all

4

3 回答 3

7

也许您的问题只是您试图用来input.element从列表中取出一个项目。这不是检查列表中元素类型的正确方法。

仅使用它来测试第一项:

bool actions(List<Object> input)
{
    var element = input.FirstOrDefault();
    if (element is String)
    {...}
    else if (element is PSObject)
    {...}
}

或者这样单独测试每个项目:

bool actions(List<Object> input)
{
    foreach (var element in input)
    {
        if (element is String)
        {...}
        else if (element is PSObject)
        {...}
    }
}

或者,如果您想确保列表的所有元素都属于给定类型,您可以使用泛型:

bool actions<T>(List<T> input)
{
    if (typeof(String).IsAssignableFrom(typeof(T))
    {...}
    else if (typeof(PSObject).IsAssignableFrom(typeof(T))
    {...}
}
于 2013-03-15T19:26:54.320 回答
2

You have to get the type of the instances in the list, not the type of the list.

Boolean actions(List<Object> input) {
  foreach (object o in input) {
    if (o is String) {
      ...
    } else if (o is PSObject) {
      ...
    }
  }
}

Alternatively, if you know that all the objects in the list are of the same type, you could check the type of the first item (input[0]) and then do the same thing to all items depending on that.

于 2013-03-15T19:28:32.640 回答
2

but input.getType().GetGenericArguments()[0] says it is object type...

Well, as List<T> is invariant, the generic argument of the list passed in will always match the generic argument of the method parameter, exactly.

In this case, the list will always be a list of objects.

Now, each item in the list may not be an object (as it's most derived type), it could be a string, or a PSObject. However you can't assume that all of them are any type other than object.

So you could check if there is a more derived type for a particular item in the list, but not of the list as a whole.

So it's more likely that you'll have to refactor the code to do:

Boolean actions(List<Object> input)
{
    foreach(object element in input)
    {
        if (element is String)
        {...}
        else if (element is PSObject)
        {...}
    }
}

If it's important for all of the items to be of the same type then you can use generics:

Boolean actions<T>(List<T> input)
{
    if (typeof(T) == typeof(string))
    {...}
    if(typeof(T) == typeof(PSObject))
    {...}
}
于 2013-03-15T19:29:37.083 回答