c# – 设置私有域的值

前端之家收集整理的这篇文章主要介绍了c# – 设置私有域的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么以下代码不工作:
class Program
{
    static void Main ( string[ ] args )
    {
        SomeClass s = new SomeClass( );

        s.GetType( ).GetField( "id",System.Reflection.BindingFlags.NonPublic ) // sorry reasently updated to GetField from GetProperty...
            .SetValue( s,"new value" );
    }
}


class SomeClass
{
    object id;

    public object Id 
    {
        get
        {
            return id;
        }
    }   
}

我正在设置一个私有字段的值.

这是我得到的exeption:

System.NullReferenceException was unhandled Message=Object reference
not set to an instance of an object. Source=ConsoleApplication7
StackTrace:
at Program.Main(String[] args) in C:\Users\Antonio\Desktop\ConsoleApplication7\ConsoleApplication7\Program.cs:line
18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean
ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,Object state)
at System.Threading.ThreadHelper.ThreadStart() InnerException:

解决方法

尝试这个(灵感来自 Find a private field with Reflection?):
var prop = s.GetType().GetField("id",System.Reflection.BindingFlags.NonPublic
    | System.Reflection.BindingFlags.Instance);
prop.SetValue(s,"new value");

我的更改是使用GetField方法 – 您正在访问一个字段而不是一个属性,以及使用NonPublic与Instance.

原文链接:https://www.f2er.com/csharp/94621.html

猜你在找的C#相关文章