Added ClassAttributeCache

This commit is contained in:
2026-01-24 17:02:15 +00:00
parent bd7edfe0d5
commit 17e86b26a6
4 changed files with 93 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System;
using UnityEngine;
namespace PashaBibko.Pacore.Runtime
{
public static class ClassAttributeCache
{
private static Dictionary<Type, List<Type>> AttributeCache { get; set; }
public static ReadOnlyCollection<Type> GetAttributesOf<T>()
{
return AttributeCache.TryGetValue(typeof(T), out List<Type> attributes) ?
attributes.AsReadOnly() :
throw new ArgumentException($"Attribute [{nameof(T)}] is not used by any classes");
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
private static void ScanAllAssemblies()
{
/* Fetches all the class types in all loaded assemblies */
Type[] classes = AppDomain.CurrentDomain.GetAssemblies() // Assembly[]
.SelectMany(assembly =>
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException err)
{
return err.Types.Where(t => t != null);
}
}) // IEnumerable<Type>
.Where(type => type.IsClass && !type.IsAbstract) // IEnumerable<Type>
.ToArray();
/* Allocates space for the cache */
AttributeCache = classes // Type[]
.Where(type => typeof(Attribute).IsAssignableFrom(type)) // IEnumerable<Type>
.ToDictionary
(
keySelector: t => t,
elementSelector: _ => new List<Type>()
); // Dictionary<Type, List<Type>>
/* Finds which attributes are attached to what classes */
foreach (Type current in classes)
{
/* Finds all the attributes of the current class */
Type[] attached = current // Type
.GetCustomAttributes(inherit: true) // object[]
.Select(attribute => attribute.GetType()) // IEnumerable<Type>
.Distinct().ToArray();
/* Adds the class type to each attribute in the dictionary */
foreach (Type attribute in attached)
{
AttributeCache[attribute].Add(current);
}
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9e0be3076f094aa2a62c814ee0a75aee
timeCreated: 1769270329

View File

@@ -0,0 +1,16 @@
{
"name": "Pacore",
"rootNamespace": "",
"references": [
"GUID:73bc4dcce6d82e44c8fe9738b987d694"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 92a828b1c98146b48b5a7061ab1e8d2e
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: