Since the Oxide API page doesn't have any examples for C# and they're actually rather hard to find on these forums, here are some I found in plugins.
Get/Setting Private Fields examples
RemoveTool.cs
Clans.csCode:static FieldInfo buildingPrivlidges;/* get a pointer to the buildingPrivlidges field */ buildingPrivlidges = typeof(BasePlayer).GetField("buildingPrivlidges", (BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic));/* get building privileges for the specified player */ List<BuildingPrivlidge> playerpriv = buildingPrivlidges.GetValue(player) as List<BuildingPrivlidge>;
Calling Private Method exampleCode:/* get pointer to the _displayName field */ FieldInfo displayName = typeof(BasePlayer).GetField("_displayName", (BindingFlags.Instance | BindingFlags.NonPublic));/* set the players new name */ displayName.SetValue(player, stripTag(player.displayName, clan));
Rust.IO
CopyPaste.csCode:/* get a pointer to the UpdateServerInformation method */ MethodInfo method = typeof(ServerMgr).GetMethod("UpdateServerInformation", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);/* call the private method */ method.Invoke(SingletonComponent<ServerMgr>.get_Instance(), new object[0]);
So some thing to note are for methods the pointer is defined as MethodInfo and for fields it's FieldInfo, also note the binding flags, one I didn't use in the examples is BindingFlags.Static but i've seen it used in code. The rest are used quite a bit. I hope that Wulf can update the API page with these or other examples as that'd save a lot of time for plugin developers who want to tap into the private stuff.Code:/* get a pointer to the Clear method */ private MethodInfo inventoryClear = typeof(ItemContainer).GetMethod("Clear", BindingFlags.NonPublic | BindingFlags.Instance);/* call the private method */ inventoryClear.Invoke(box.inventory, null);
Reflection examples for private methods and fields (C#)
Discussion in 'Rust Development' started by Caffeine, Jul 15, 2016.