add TryProxy for any objects

This commit is contained in:
Shockah 2022-02-10 16:26:43 +01:00
parent 467375a7a3
commit a54d58d064
2 changed files with 33 additions and 0 deletions

View File

@ -98,5 +98,31 @@ namespace StardewModdingAPI.Framework.ModHelpers
return castApi;
return this.ProxyFactory.CreateProxy<TInterface>(api, this.ModID, uniqueID);
}
/// <inheritdoc />
public bool TryProxy<TInterface>(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;
}
}
}
}

View File

@ -25,5 +25,12 @@ namespace StardewModdingAPI
/// <typeparam name="TInterface">The interface which matches the properties and methods you intend to access.</typeparam>
/// <param name="uniqueID">The mod's unique ID.</param>
TInterface GetApi<TInterface>(string uniqueID) where TInterface : class;
/// <summary>Try to proxy (or unproxy back) the given object to a given interface provided by a mod.</summary>
/// <typeparam name="TInterface">The interface type to proxy (or unproxy) to.</typeparam>
/// <param name="uniqueID">The mod's unique ID.</param>
/// <param name="toProxy">The object to try to proxy (or unproxy back).</param>
/// <param name="proxy">The reference to store the proxied (or unproxied) object back.</param>
bool TryProxy<TInterface>(string uniqueID, object toProxy, out TInterface proxy) where TInterface : class;
}
}