【问题标题】:Need to cast to an object without knowing what type the object is需要在不知道对象是什么类型的情况下强制转换为对象
【发布时间】:2011-02-10 23:59:22
【问题描述】:

我正在尝试根据设置动态加载我的身份验证服务器类型。当我不知道类型时,我很想知道如何转换为类型。

   Type t = Type.GetType(WebConfigurationManager.AppSettings.Get("AuthenticationSvcImpl"));
    IAuthenticationService authCli = Activator.CreateInstance(t);
    return authCli.AuthenticateUser(login);

我知道有 Convert.ChangeType(),但它只是转换为一个对象...

【问题讨论】:

    标签: c# reflection interface casting


    【解决方案1】:
    var authCli = Activator.CreateInstance(t) as IAuthenticationService;
    

    【讨论】:

    • 这成功了……虽然不太明白——为什么是 var?
    • var 只是为了节省空间,否则行太长了,我懒得拆分它:) var == IAuthenticationService 在这种情况下。基本上,您的类型在编译时是已知的,而不是实际类型,而是兼容的接口类型。
    【解决方案2】:

    这就是你要找的吗?

    Type t = Type.GetType(WebConfigurationManager.AppSettings.Get("AuthenticationSvcImpl"));
    IAuthenticationService authCli = (IAuthenticationService) Activator.CreateInstance(t);
    return authCli.AuthenticateUser(login);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 2022-10-24
      • 1970-01-01
      相关资源
      最近更新 更多