From a54d58d064df5654e845f9b2b4fc9db5b0189db0 Mon Sep 17 00:00:00 2001 From: Shockah Date: Thu, 10 Feb 2022 16:26:43 +0100 Subject: add TryProxy for any objects --- .../Framework/ModHelpers/ModRegistryHelper.cs | 26 ++++++++++++++++++++++ src/SMAPI/IModRegistry.cs | 7 ++++++ 2 files changed, 33 insertions(+) (limited to 'src') diff --git a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs index ef1ad30c..92c52b00 100644 --- a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs @@ -98,5 +98,31 @@ namespace StardewModdingAPI.Framework.ModHelpers return castApi; return this.ProxyFactory.CreateProxy(api, this.ModID, uniqueID); } + + /// + public bool TryProxy(string uniqueID, object toProxy, out TInterface proxy) where TInterface : class + { + try + { + foreach (var toProxyInterface in toProxy.GetType().GetInterfaces()) + { + var unproxyBuilder = this.ProxyFactory.ObtainBuilder(typeof(TInterface), toProxyInterface, this.ModID, uniqueID); + if (unproxyBuilder.TryUnproxy(toProxy, out object targetInstance)) + { + proxy = (TInterface)targetInstance; + return true; + } + } + + var proxyBuilder = this.ProxyFactory.ObtainBuilder(toProxy.GetType(), typeof(TInterface), this.ModID, uniqueID); + proxy = (TInterface)proxyBuilder.ObtainInstance(toProxy, this.ProxyFactory); + return true; + } + catch + { + proxy = null; + return false; + } + } } } diff --git a/src/SMAPI/IModRegistry.cs b/src/SMAPI/IModRegistry.cs index 10b3121e..9b99e459 100644 --- a/src/SMAPI/IModRegistry.cs +++ b/src/SMAPI/IModRegistry.cs @@ -25,5 +25,12 @@ namespace StardewModdingAPI /// The interface which matches the properties and methods you intend to access. /// The mod's unique ID. TInterface GetApi(string uniqueID) where TInterface : class; + + /// Try to proxy (or unproxy back) the given object to a given interface provided by a mod. + /// The interface type to proxy (or unproxy) to. + /// The mod's unique ID. + /// The object to try to proxy (or unproxy back). + /// The reference to store the proxied (or unproxied) object back. + bool TryProxy(string uniqueID, object toProxy, out TInterface proxy) where TInterface : class; } } -- cgit