2016-03-07 99 views
1

我做了一个程序,我想根据参数类型转换所有值,这是通过运行时方法得到的,我想要的是将所有值用户在文本框中输入参数的定义类型。 我想要的是将字符串类型转换为int,float,decimal等类型在运行时C#

private object convertType(Type type, string value) 
    { 
     Type t = typeof(int); 
     //suppose value have stringvalue=33; 
     return 33; //of type int 
    } 

有什么办法得到任何对象类型?

更新回答

为@Atmane EL BOUACHRI,

class Program 
{ 
static void Main() 
{ 

    var ints = ConvertType<int>("33"); 
    var bools = ConvertType<bool>("false"); 
    var decimals = ConvertType<decimal>("1.33m"); // exception here 
    Console.WriteLine(ints); 
    Console.WriteLine(bools); 
    Console.WriteLine(decimals); 

    Console.ReadLine(); 
} 

public static T ConvertType<T>(string input) 
{ 
    T result = default(T); 
    var converter = TypeDescriptor.GetConverter(typeof(T)); 
    if (converter != null) 
    { 
     try 
     { 
      result = (T)converter.ConvertFromString(input); 
     } 
     catch 
     { 
      // add you exception handling 
     } 
    } 
    return result; 
} 
} 

在这里,我不想硬编码<int><string><decimal>,我要的是

private object convertToAnyType(Type type, string value) 
{ 
    //Type t = typeof(int); 
    return ConvertType<type>("33"); 
} 

有什么办法吗?

+1

你可能不得不使用泛型。 –

+0

我做了一个动态的Web服务调用,其中任何Web服务都被我的项目占用,但是我被卡住了不同类型的参数,我如何处理不同方法的所有参数? –

+1

'Convert.ChangeType'将适用于有限范围的内置类型 –

回答

1

你的意思是肯定返回字符串值解析为一个特定的类型。然后,我提出泛型。具体方法如下:

1) - 没有泛型(我在2喜欢用仿制) - )

class Program 
    { 
     static void Main() 
     { 

      var ints = (int)ConvertType(typeof(int),"33"); 
      var bools = (bool)ConvertType(typeof(bool), "true"); 

      Console.WriteLine(bools); 
      Console.WriteLine(ints); 

      Console.ReadLine(); 
     } 

     public static object ConvertType(Type type, string input) 
     { 
      object result = default(object); 
      var converter = TypeDescriptor.GetConverter(type); 
      if (converter != null) 
      { 
       try 
       { 
        result = converter.ConvertFromString(input); 
       } 
       catch 
       { 
        // add you exception handling 
       } 
      } 
      return result; 
     } 
    } 

2) - 随着通用

class Program 
{ 
    static void Main() 
    { 

     var ints = ConvertType<int>("33"); 
     var bools = ConvertType<bool>("false"); 
     var decimals = ConvertType<decimal>("1.33m"); // exception here 
     Console.WriteLine(ints); 
     Console.WriteLine(bools); 
     Console.WriteLine(decimals); 

     Console.ReadLine(); 
    } 

    public static T ConvertType<T>(string input) 
    { 
     T result = default(T); 
     var converter = TypeDescriptor.GetConverter(typeof(T)); 
     if (converter != null) 
     { 
      try 
      { 
       result = (T)converter.ConvertFromString(input); 
      } 
      catch 
      { 
       // add you exception handling 
      } 
     } 
     return result; 
    } 
} 

HPE它有助于

+0

在我的情况下,这不起作用 int t = 0; int ints = oo.ConvertType (“33”); –

+0

@ user6002727我不明白 – Coding4Fun

+0

我不知道哪种类型来自另一端,所以我怎么能称为“convertType ”,其中g是像int,浮点等任何变量 –

相关问题