简体   繁体   English

动态转换类型对象到类型(某些类)

[英]Dynamicly Converting Type Object to Type (Some Class)

I would like some of my methods take an Object and convert it in to a useable type: 我希望我的一些方法获取一个Object并将其转换为可用类型:

*Simple example *简单的例子

public void PostAction (object act){
    object Action = (act.GetType) act;
    string ActionName = Action.PostName;
}

From doing a little looking around the internet and Stackoverflow, I have found only ways to call an object's methods without a type 通过稍微浏览一下互联网和Stackoverflow,我发现只有在没有类型的情况下调用对象方法的方法

public void PostAction (object act){
    Type t = act.GetType(); // myObject.GetType() would also work
    MethodInfo GetPostName = t.GetMethod("GetPostName");
    GetPostName.Invoke(act, null);
}

Is there a better way? 有没有更好的办法? Can I cast a Object to its Type?? 我可以将一个对象转换为它的类型??

You could use dynamic : 你可以使用dynamic

public void PostAction (object act){
    ((dynamic)act).GetPostName();
}

But I would go further and change the approach: 但我会进一步改变方法:

  1. Declare interface with your GetPostName method: 使用GetPostName方法声明接口:

     public interface IMyInterface { void GetPostName(); } 
  2. Implement the interface in your class 在您的类中实现接口

  3. Change PostAction method to take IMyInterface parameter: 更改PostAction方法采取IMyInterface参数:

     public void PostAction(IMyInterface act) 
  4. Use the interface method withing PostAction method: 使用PostAction方法的接口方法:

     public void PostAction(IMyInterface act) { act.GetPostName(); } 

Benefits: 优点:

  • would give you a compile-time type safety 会给你一个编译时类型的安全性
  • would be faster, because wouldn't require reflection 会更快,因为不需要反射

You should actually never use reflection to invoke a method of an object you pass in. And it is also not really best practice to use object as parameter type of a method. 实际上,您应该永远不要使用反射来调用传入的对象的方法。使用object作为方法的参数类型也不是最佳实践。 You usually want your code strongly typed. 您通常希望您的代码是强类型的。

Anyways, if you want "object" as the type of your parameter, simply cast the object to an interface or type: 无论如何,如果您希望“对象”作为参数的类型,只需将对象强制转换为接口或键入:

    public interface IMyInterface
    {
        string GetPostName();
    }

    public void PostAction(object actObject)
    {
        var action = actObject as IMyInterface;
        if (action != null)
        {
            var postName = action.GetPostName();
        }
    }

If you cast like this, the result can be null if the object does not implement that interface, thats why you might want to check against null... 如果像这样进行转换,如果对象没有实现该接口,结果可以为null,这就是为什么你可能要检查null ...

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

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