在c#中通过字符串变量初始化一个类? [英] initialize a class by string variable in c#?

查看:470
本文介绍了在c#中通过字符串变量初始化一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过字符串变量初始化一个类?我有PHP代码。

is it possible to initialize a class by a string variable? I have code in PHP.

<?php
  $classname = "test";

  $oTest = new $classname();

  class test{
  }
?>

如何在c#中执行此操作?

how do I do this in c#?

推荐答案

System.Activator.CreateInstance(Type.GetType(className))

但是,问题是C#3.0是一个静态类型语言。你不能在返回的对象上调用随机方法。你可以让你可以实例化的类实现一些通用接口,并将上述表达式的结果转换到接口或手动使用反射来调用返回的对象上的方法。

The problem, however, is that C# 3.0 is a statically typed language. You can't just call random methods on the returned object. You can have the classes you might instantiate implement some common interface and cast the result of the above expression to the interface or manually use reflection to call methods on the returned object.

这篇关于在c#中通过字符串变量初始化一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆