简体   繁体   English

如何转换为IList类型?

[英]How do I convert to the type IList?

I want to achieve the effects of putting in random numbers in an IList and it seems I am unable to think of how to get the type of the IList , whether an int or decimal , etc. I cannot simply cast the Console.ReadLine() to the type of the IList . 我想实现将随机数放入IList的效果,并且似乎无法考虑如何获取IList的类型(无论是int还是decimal等)。我不能简单地转换Console.ReadLine()IList的类型。

public void RandomizeIList<T>(IList<T> list)
{
    randomNum = new Random();
    T typeRead = 0, typeReadSeed = 0;
    String strRead = "", strReadSeed = "";
    Console.WriteLine("How many {0}s do you want to randomly generate?", list.GetType());
    T strRead = (list.GetType())Console.ReadLine();
    Console.WriteLine("What's the limit of the randomly generated {0}s?", list.GetType());
    Int32.TryParse(strReadSeed, out intReadSeed);
    for (int i = 0; i < strRead; i++)
    {
        list[i] = randomNum.Next(intReadSeed);
    }
}

Syntactically what you want is: 语法上您想要的是:

T strRead = (T)Console.ReadLine();

However, Console.ReadLine only returns a string, so this cast (and the use of generics) makes no sense. 但是, Console.ReadLine 返回一个字符串,因此这种强制转换(以及使用泛型)毫无意义。 Either you should be using a IList<string> (because you think T is a string) or you should be using IList<int> (because you are adding int s to the list). 您应该使用IList<string> (因为您认为T是一个字符串),还是应该使用IList<int> (因为您将int添加到列表中)。 In any case, it's very unclear what you are trying to accomplish, since you are doing nothing with strRead . 无论如何,由于strRead不执行任何操作,因此尚不清楚您要完成什么。

Update, per comment : 根据评论更新

Certainly, you can convert a string to an arbitrary type. 当然,您可以将字符串转换为任意类型。 The framework provides some utilities for this, such as the Convert class: 该框架为此提供了一些实用程序,例如Convert类:

T strRead = (T)(object)Convert.ChangeType(Console.ReadLine(), typeof(T));

This will work for simple types -- you can use Convert to convert a string to an int , for example. 这将适用于简单类型-例如,您可以使用Convertstring Convertint However, it should go without saying that you can't use this class to convert any arbitrary string to any arbitrary type. 但是,不用说您不能使用此类将任意字符串转换为任意类型。 For that, you will have to consider your own type conversion framework, perhaps combining the behaviors of Convert , with implicit and explicit conversions, etc. This is because it's clear that the string representation of a particular type is entirely dependent on the characteristics of that type. 为此,您将必须考虑自己的类型转换框架,也许将Convert的行为与隐式和显式转换等结合起来。这是因为很明显,特定类型的字符串表示形式完全取决于该类型的特性。类型。

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

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