繁体   English   中英

运行时 c# 中的动态转换

[英]Dynamic cast in c# in runtime

如您所见,我有两个课程:

  static void Main(string[] args)
    {

        object m = (??????)"salam";
    }


public class A
{
    public string name { set; get; }
    public static implicit operator A(string _name)
    {
        A aa = new A();
        aa.name = _name;
        return aa;
    }
}
public class B
{
    public string family { set; get; }
    public static implicit operator B(string _family)
    {
        B bb = new B();
        bb.family = _family;
        return bb;
    }
}

我需要在运行时在这一行中转换我的字符串:

object m = (??????)"salam";

是否有任何解决方案可以将我的 class 名称作为字符串传递来转换我的值。例如在运行时我需要将“salam”转换为A或者B

static 演员像这样工作得很好

 object m = (A)salam";
 object m = (B)"salam";

但我需要在运行时转换我的字符串

Type x=null;
If(condition) 
x can be type of A
else 
x can be type of B

object m = (x)"salam";

您需要使用接口来满足这种需求。 以下代码显示了如何执行此操作。

为了模拟您的情况,我编写了一个基于时间返回AB的方法。 这里的list包含一堆可能是类型AB的对象,具体取决于执行的第二个。 在现实世界的场景中,您可以通过其他各种方式获取您的类型。

public class StackOverflowQuestion
{
    public static void Run()
    {
        List<IBase> list = new List<IBase>();
        string types = "";
        for (int i = 0; i < 10; i++)
        {
            var randomType = GiveMeARandomIBaseType();
            System.Threading.Thread.Sleep(750);
            IBase hello = randomType.Convert("salam");
            list.Add(hello);
            types += hello.GetType().Name + ",";
        }

        types = types.Trim(',');
        //sample result : B,B,A,B,A,A,B,A,B,B
    }

    static IBase GiveMeARandomIBaseType() {
        if (DateTime.Now.Second % 2 == 0)
            return new A();
        else
            return new B();
    }
}

public interface IBase {
    public IBase Convert(string s);
}
public static class MyExtensions {
    public static T Convert<T>(this string str, IBase b) where T : IBase {
        try
        {
            return (T)b.Convert(str);
        }
        catch (Exception)
        {
            return default;
        } 
    }
}
public class A : IBase
{
    public IBase Convert(string s) {
        return (A)s;
    }
    public string name { set; get; }

    public static implicit operator A(string _name)
    {
        A aa = new A();
        aa.name = _name;
        return aa;
    }
}
public class B : IBase
{

    public IBase Convert(string s)
    {
        return (B)s;
    }
    public string family { set; get; }
    public static implicit operator B(string _family)
    {
        B bb = new B();
        bb.family = _family;
        return bb;
    }
}

我有一个类似的问题,经过所有的研究和时间,我能够通过以下方式接近预期的结果。 我使用内部方法访问(内部)class,此方法返回所需的转换结果。

第 1 步:在 class

public class A
    {
       public string Name { set; get; }

        public static implicit operator A(string name)
        {
            return new A
            {
                Name = name
            };
        }

        public A GetCasting(object a)
        {
            A i = (A)a;
            return i;
        }
    }

    public class B
    {
        public string Family { set; get; }

        public static implicit operator B(string family)
        {
            return new B
            {
                Family = family
            };
        }
        public B GetCasting(object b)
        {
            B i = (B)b;
            return i;
        }
    }

第 2 步:在 controller 或代码中

    var className = "A";
    var classMethod = "GetCasting";
    var classType = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsClass && t.Name == className).FirstOrDefault();
    var classInstance = Activator.CreateInstance(classType);
    var castMethod = classType.GetMethod(classMethod);
    var yourObject = "salam";
    var objectData = new object[] { yourObject };
    var resultObject = castMethod.Invoke(classInstance, objectData);

暂无
暂无

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

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