【问题标题】:Something like Reflections in Java for .NET [closed].NET 的 Java 中的反射之类的东西 [关闭]
【发布时间】:2012-10-05 12:21:03
【问题描述】:

【问题讨论】:

  • 是的,它叫做反射。你想知道什么?
  • 任何教程如何在.Net中使用它?
  • 您可以轻松地在 Google 上搜索此内容并自己找到答案。请原谅我说我发现你没有在这方面付出任何努力......谷歌:“.NET Reflection”@Jeff:感谢删除答案提示:)

标签: .net c#-4.0 reflection


【解决方案1】:

Reflection 提供了封装程序集、模块和类型的对象(Type 类型)。您可以使用反射来动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性

我已经使用反射来动态加载程序集并在反射的帮助下显示其形式。

Step 1: Loading an assembly form the specified path.

string path = Directory.GetCurrentDirectory() + @"\dynamicdll.dll";
try
{
    asm = Assembly.LoadFrom(path);
}
catch (Exception)
{
}

Step 2: Getting all forms of an assembly dynamically & adding them to the list type.

List<Type> FormsToCall = new List<Type>();
Type[] types = asm.GetExportedTypes();
foreach (Type t in types)
{
    if (t.BaseType.Name == "Form")
        FormsToCall.Add(t);
}

Step 3:

int FormCnt = 0;
Type ToCall;
while (FormCnt < FormsToCall.Count)
{
     ToCall = FormsToCall[FormCnt];
     //Creates an instance of the specified type using the constructor that best matches the specified parameters.
     object ibaseObject = Activator.CreateInstance(ToCall);
     Form ToRun = ibaseObject as Form;
     try
     {
          dr = ToRun.ShowDialog();
          if (dr == DialogResult.Cancel)
          {
             cancelPressed = true;
             break;
          }
          else if (dr == DialogResult.Retry)
          {
             FormCnt--;
             continue;
          }
     }
     catch (Exception)
     {
     }
     FormCnt++;
}

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2011-12-29
    • 2020-11-10
    • 1970-01-01
    相关资源
    最近更新 更多