将变量转换为仅在运行时已知的类型?


83
foreach (var filter in filters)
{
    var filterType = typeof(Filters);
    var method = filterType.GetMethod(filter, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static);
    if (method != null)
    {
        var parameters = method.GetParameters();
        Type paramType = parameters[0].ParameterType;
        value = (string)method.Invoke(null, new[] { value });
    }
}

我怎样才能投valueparamTypevaluestringparamType很可能只是一个基本的类型一样intstring或者可能float。如果无法进行转换,我会抛出异常很酷。




4
@MichaelFreidgeim的评论可能与前面的评论重复。
kmote

1
@kmote,通常是在有人投票以重复形式结束问题时自动生成“可能重复”的注释。不知道为什么系统第二次插入相同的注释,而不是第一个注释的增量表决。可能是最早的注释是手动创建的,因为它在“可能”中具有小写的p
Michael Freidgeim,

Answers:


88

您使用的所有类型都实现IConvertible。因此,您可以使用ChangeType

 value = Convert.ChangeType(method.Invoke(null, new[] { value }), paramType);

12
很棒...单行。var value = Convert.ChangeType(objectValue,objectType);
Rigin

17

您可以充满活力;例如:

using System;

namespace TypeCaster
{
    class Program
    {
        internal static void Main(string[] args)
        {
            Parent p = new Parent() { name = "I am the parent", type = "TypeCaster.ChildA" };
            dynamic a = Convert.ChangeType(new ChildA(p.name), Type.GetType(p.type));
            Console.WriteLine(a.Name);

            p.type = "TypeCaster.ChildB";
            dynamic b = Convert.ChangeType(new ChildB(p.name), Type.GetType(p.type));
            Console.WriteLine(b.Name);
        }
    }

    internal class Parent
    {
        internal string type { get; set; }
        internal string name { get; set; }

        internal Parent() { }
    }

    internal class ChildA : Parent
    {
        internal ChildA(string name)
        {
            base.name = name + " in A";
        }

        public string Name
        {
            get { return base.name; }
        }
    }

    internal class ChildB : Parent
    {
        internal ChildB(string name)
        {
            base.name = name + " in B";
        }

        public string Name
        {
            get { return base.name; }
        }
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.