将对象转换为与IEnumerable集合相同的类型

时间:2018-09-14 00:49:39

标签: c#

从本质上讲,我具有接受参数的函数: const winston = require('winston'); const winstonRotator = require('winston-daily-rotate-file'); const { combine, timestamp, label, printf } = winston.format; var rotatorOptions = { level: 'info', filename: './logs/app-%DATE%.log', datePattern: 'MM-DD-YYYY', handleExceptions: true, zippedArchive: false, maxsize: '10m', maxFiles: '15d', }; const logger =winston.createLogger({ format: combine( label({ label: 'APP' }), timestamp(), printf(info => {return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`; }) ), 'transports': [ new winstonRotator(rotatorOptions) ] });

我需要使用Equals()检查集合ContainsValue(IEnumerable collection, object obj) obj

具体来说,collection是一个字符串数组,而obj是一个自定义类型/类(它叫做FString,我不完全了解它是什么,但至少是从字符串派生的。)

不幸的是,解决方案需要通用,因此我无法显式引用自定义类型。

因此,我需要一种将obj普遍转换为集合类型的方法。 这可能吗?

编辑:

Contains

4 个答案:

答案 0 :(得分:2)

您应该只可以在if语句中使用它:

if(object.Equals(element, obj))

然后您根本不需要强制转换,也不必担心null等问题。

答案 1 :(得分:0)

细节非常模糊,但是Enumerable.Cast(IEnumerable) Method可能会有帮助。

Doco,例如here

 System.Collections.ArrayList fruits = new System.Collections.ArrayList();
 fruits.Add("mango");
 fruits.Add("apple");
 fruits.Add("lemon");

 IEnumerable<string> query =
     fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);

 // The following code, without the cast, doesn't compile.
 //IEnumerable<string> query1 =
 //    fruits.OrderBy(fruit => fruit).Select(fruit => fruit);

 foreach (string fruit in query)
 {
     Console.WriteLine(fruit);
 }

 // This code produces the following output: 
 //
 // apple 
 // lemon
 // mango

答案 2 :(得分:0)

您可以这样使用它(如果您可以访问集合的字段):

string objAsString = obj?.ToString() ?? "";

if(collection.Any(x => x.field == objAsString))
{
    //Do something...
}

答案 3 :(得分:0)

  

因此,我需要一种将obj普遍转换为集合类型的方法。这可能吗?

如果这是您唯一的问题,那么解决方案很容易。如果您还需要其他功能,请修改您的问题。

static bool ContainsValue<T>(IEnumerable<T> collection, object obj) where T : class
{
    var compareTo = obj as T;
    if (obj == null) return false;  //Return false if cast was not possible
    foreach (var item in collection) 
    {
        if (item == obj) return true;
    }
    return false;
}

您还可以强制调用方进行强制转换,这似乎是更明智的处理方式,因为这样您就可以在编译时强制执行类型安全。您也可以使用少量的LINQ来缩短代码。

static bool ContainsValue<T>(IEnumerable<T> collection, T obj) where T : class
{
    return collection.Any( item => item == obj );
}
相关问题