Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么不是';有没有一种与Java';可以在.NET中访问设置吗?_Java_.net_Reflection - Fatal编程技术网

为什么不是';有没有一种与Java';可以在.NET中访问设置吗?

为什么不是';有没有一种与Java';可以在.NET中访问设置吗?,java,.net,reflection,Java,.net,Reflection,看一看-Java中允许您通过反射调用私有方法的一种方法。为什么.NET还没有实现这样的功能?就是在.NET中实现这一功能的一个例子 using System; using System.Reflection; using System.Collections.Generic; public class MyClass { public static void Main() { try { Console.WriteLine("

看一看-Java中允许您通过反射调用私有方法的一种方法。为什么.NET还没有实现这样的功能?

就是在.NET中实现这一功能的一个例子

using System;
using System.Reflection;
using System.Collections.Generic;

public class MyClass
{
   public static void Main()
   {
        try
        {
            Console.WriteLine("TestReflect started.");
            TestReflect test = new TestReflect();
            Console.WriteLine("TestReflect ended.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        ConsoleKeyInfo cki;
        do
        {
            Console.WriteLine("Press the 'Q' key to exit.");
            cki = Console.ReadKey(true);
        } while (cki.Key != ConsoleKey.Q);
   }
}

public class TestReflect
{
   public TestReflect()
   {
        this.GetType().GetMethod("PublicMethod").Invoke(this, null);
        this.GetType().GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
   }

   public void PublicMethod()
   {
        Console.WriteLine("PublicMethod called");
   }

   private void PrivateMethod()
   {
        Console.WriteLine("FTW!one1");
   }
 }
我认为“为什么”可能是一个推测性的问题,但如果您正在寻找一种测试私有方法的方法,我认为使用.NET 4.0可以更轻松地做到这一点:


您可以使用反射来调用私有方法,尽管它不像调用公共方法那样直截了当。我们以前在单元测试中做过这项工作,并使用以下文章作为操作参考:


在.NET中,使用反射可以访问任何私有内容

例如,在类栏上获取名为Foo的私有实例方法的访问权限如下所示:

typeof(Bar).GetMethod("Foo",BindingFlags.NonPublic | BindingFlags.Instance);
但是,它确实要求使用反射的代码是完全可信的


(V4的安全要求不同)

链接已断开。如果你在网站被关闭之前从网站上复制了一些有用的信息,那就太好了,现在这个被接受的答案是没有帮助的。@NightOwl888,为你修复了它。