summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
diff options
context:
space:
mode:
authorJesse Plamondon-Willard <github@jplamondonw.com>2017-12-12 01:00:32 -0500
committerJesse Plamondon-Willard <github@jplamondonw.com>2017-12-12 01:00:32 -0500
commit0e43041777d68b96f110fa38ad7424b855db761a (patch)
treef80a166ef3eb0abc0671dff1ba70593479178d55 /src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
parentd04cacbdd0729140e4d8e93323ba66ee90ff9d2a (diff)
downloadSMAPI-0e43041777d68b96f110fa38ad7424b855db761a.tar.gz
SMAPI-0e43041777d68b96f110fa38ad7424b855db761a.tar.bz2
SMAPI-0e43041777d68b96f110fa38ad7424b855db761a.zip
add support for casting mod-provided API to an interface without a direct assembly reference (#409)
Diffstat (limited to 'src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs')
-rw-r--r--src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs24
1 files changed, 24 insertions, 0 deletions
diff --git a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
index 827c77d5..68201d9a 100644
--- a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
+++ b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Linq;
+using ImpromptuInterface;
namespace StardewModdingAPI.Framework.ModHelpers
{
@@ -62,5 +63,28 @@ namespace StardewModdingAPI.Framework.ModHelpers
this.Monitor.Log($"Accessed mod-provided API for {mod.DisplayName}.", LogLevel.Trace);
return mod?.Api;
}
+
+ /// <summary>Get the API provided by a mod, mapped to a given interface which specifies the expected properties and methods. If the mod has no API or it's not compatible with the given interface, get <c>null</c>.</summary>
+ /// <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>
+ public TInterface GetApi<TInterface>(string uniqueID) where TInterface : class
+ {
+ // validate
+ if (!typeof(TInterface).IsInterface)
+ {
+ this.Monitor.Log("Tried to map a mod-provided API into a class; must be an interface.");
+ return null;
+ }
+
+ // get raw API
+ object api = this.GetApi(uniqueID);
+ if (api == null)
+ return null;
+
+ // get API of type
+ if (api is TInterface castApi)
+ return castApi;
+ return api.ActLike<TInterface>();
+ }
}
}