简体   繁体   English

声明不同类型的变量foreach

[英]Declare variable of different type foreach

I'm working with IMAP and POP3 mail in c# and I met a curious problem. 我正在用C#处理IMAP和POP3邮件,遇到一个奇怪的问题。 The uid (Unique ID) for the two type are different types: for the IMAP is long variable and for the POP is a string. 两种类型的uid(唯一ID)是不同的类型:IMAP是long变量,而POP是字符串。 So, the function to download and save the mails are equal except for that. 因此,除此之外,下载和保存邮件的功能是相同的。 I need to do a foreach loop but the only line that change is the first: 我需要做一个foreach循环,但唯一改变的是第一行:

foreach (long uid in uids) //for the imap
foreach (string uid in uids) //for the pop

I can't declare uid first, so, there is a way to duplicate only this line but not the entire function? 我不能先声明uid,因此,有一种方法仅复制此行而不复制整个函数?

Based on your statement of how you'll be using it: 根据您的用法说明:

foreach (object uid in uids)
{
    string uidStr = uid.ToString();
    // use uidStr, e.g.
    string myPath = Path.Combine(@"C:\mail\", uidStr);

Or: 要么:

foreach (string uid in uids.Select(x => x.ToString()))

Just do 做就是了

foreach (long uid in uids.OfType<long>())
foreach (string uid in uids.OfType<string>())

(But I don't have enough context from your question to give a more detailed answer.) (但是您的问题我没有足够的背景信息,无法给出更详细的答案。)

[EDIT] [编辑]

If I take your meaning correctly, you could define your process method like so: 如果我正确理解了您的意思,则可以这样定义您的处理方法:

static void process(IEnumerable<string> uids)
{
    foreach (string uid in uids)
    {
        // ...
    }
}

And then call it like this: 然后这样称呼它:

process(uids.OfType<int>().Select(uid => uid.ToString()));
process(uids.OfType<string>());

您可以为此使用动态

foreach (dynamic uid in uids)

What happened to the use of var?? 使用var发生了什么?

foreach (var uid in uids)

?? ?? or have i completely misunderstood the question? 还是我完全误解了这个问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM