Here are the examples of the csharp api System.Type.GetInterfaces() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1715 Examples
19
Source : CelesteNetUtils.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public static Type GetRequestType(this Type t) {
Type[] interfaces = t.GetInterfaces();
foreach (Type i in interfaces)
if (i.IsConstructedGenericType && i.GetGenericTypeDefinition() == typeof(IDataRequestable<>))
return i.GetGenericArguments()[0];
throw new Exception($"Invalid requested type: {t.FullName}");
}
19
Source : TypeExtensions.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public static bool IsImplementType(this Type serviceType, Type implementType)
{
//泛型
if (serviceType.IsGenericType)
{
if (serviceType.IsInterface)
{
var interfaces = implementType.GetInterfaces();
if (interfaces.Any(m => m.IsGenericType && m.GetGenericTypeDefinition() == serviceType))
{
return true;
}
}
else
{
if (implementType.BaseType != null && implementType.BaseType.IsGenericType && implementType.BaseType.GetGenericTypeDefinition() == serviceType)
{
return true;
}
}
}
else
{
if (serviceType.IsInterface)
{
var interfaces = implementType.GetInterfaces();
if (interfaces.Any(m => m == serviceType))
return true;
}
else
{
if (implementType.BaseType != null && implementType.BaseType == serviceType)
return true;
}
}
return false;
}
19
Source : ServiceCollectionExtensions.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public static IServiceCollection AddServicesFromreplacedembly(this IServiceCollection services, replacedembly replacedembly)
{
foreach (var type in replacedembly.GetTypes())
{
#region ==单例注入==
var singletonAttr = (SingletonAttribute)Attribute.GetCustomAttribute(type, typeof(SingletonAttribute));
if (singletonAttr != null)
{
//注入自身类型
if (singletonAttr.Itself)
{
services.AddSingleton(type);
continue;
}
var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
if (interfaces.Any())
{
foreach (var i in interfaces)
{
services.AddSingleton(i, type);
}
}
else
{
services.AddSingleton(type);
}
continue;
}
#endregion
#region ==瞬时注入==
var transientAttr = (TransientAttribute)Attribute.GetCustomAttribute(type, typeof(TransientAttribute));
if (transientAttr != null)
{
//注入自身类型
if (transientAttr.Itself)
{
services.AddSingleton(type);
continue;
}
var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
if (interfaces.Any())
{
foreach (var i in interfaces)
{
services.AddTransient(i, type);
}
}
else
{
services.AddTransient(type);
}
continue;
}
#endregion
#region ==Scoped注入==
var scopedAttr = (ScopedAttribute)Attribute.GetCustomAttribute(type, typeof(ScopedAttribute));
if (scopedAttr != null)
{
//注入自身类型
if (scopedAttr.Itself)
{
services.AddSingleton(type);
continue;
}
var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
if (interfaces.Any())
{
foreach (var i in interfaces)
{
services.AddScoped(i, type);
}
}
else
{
services.AddScoped(type);
}
}
#endregion
}
return services;
}
19
Source : TypeUtils.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static List<MemberInfo> GetAllInterfaceMembers(this Type type)
{
Stack<Type> pending = new Stack<Type>();
pending.Push(type);
List<MemberInfo> ret = new List<MemberInfo>();
while (pending.Count > 0)
{
Type current = pending.Pop();
ret.AddRange(current.GetMembers());
if (current.BaseType != null)
{
pending.Push(current.BaseType);
}
foreach (Type x in current.GetInterfaces())
{
pending.Push(x);
}
}
return ret;
}
19
Source : ICollectionResolver.cs
with MIT License
from 1996v
with MIT License
from 1996v
internal static bool TypeIsCollection(Type t, out ConstructorInfo constructor, out Type itemType, out bool isImplGenerIList, out bool IsImplIList, out bool isImplGenerICollec, out bool isImplIReadOnlyList)
{
constructor = null;
itemType = null;
IsImplIList = false;
isImplGenerIList = false;
isImplGenerICollec = false;
isImplIReadOnlyList = false;
if (t.IsInterface)
{
if (t == typeof(IEnumerable) || t == typeof(ICollection) || t == typeof(IList))
{
itemType = typeof(object);
if (t == typeof(IList))
{
IsImplIList = true;
}
return true;
}
if (t.IsGenericType)
{
Type genericType = t.GetGenericTypeDefinition();
if (genericType == typeof(IEnumerable<>) || genericType == typeof(IList<>) || genericType == typeof(ICollection<>) || genericType == typeof(ISet<>) || genericType == typeof(IReadOnlyList<>) || genericType == typeof(IReadOnlyCollection<>))
{
if (genericType == typeof(IList<>))
{
isImplGenerIList = true;
isImplGenerICollec = true;
}
else if (genericType == typeof(ICollection<>) || genericType == typeof(ISet<>))
{
isImplGenerICollec = true;
}
else if (genericType == typeof(IReadOnlyList<>))
{
isImplIReadOnlyList = true;
}
itemType = t.GetGenericArguments()[0];
return true;
}
}
return false;
}
if (t.IsGenericType)
{
Type genericType = t.GetGenericTypeDefinition();
if (genericType == typeof(List<>))
{
itemType = t.GetGenericArguments()[0];
isImplGenerIList = true;
IsImplIList = true;
isImplGenerICollec = true;
isImplIReadOnlyList = true;
constructor = t.GetConstructor(new Type[] { typeof(int) });
return true;
}
}
bool isImplGenerIEnumerable = false;
bool isImplICollection = false;
Type generIEnumerableItemType = null;
Type generILisreplacedemType = null;
Type generICollectionItemType = null;
Type[] intserfaces = t.GetInterfaces();
foreach (Type item in intserfaces)
{
if (item.IsGenericType)
{
Type genericTypeDefinition = item.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IEnumerable<>))
{
isImplGenerIEnumerable = true;
generIEnumerableItemType = item.GetGenericArguments()[0];
}
else if (genericTypeDefinition == typeof(ICollection<>))
{
isImplGenerICollec = true;
generICollectionItemType = item.GetGenericArguments()[0];
}
else if (genericTypeDefinition == typeof(IList<>))
{
isImplGenerIList = true;
generILisreplacedemType = item.GetGenericArguments()[0];
}
}
else if (item == typeof(ICollection))
{
isImplICollection = true;
}
else if (item == typeof(IList))
{
IsImplIList = true;
}
}
if (isImplGenerIList)
{
if (TryGetConstructorInfo(t, generILisreplacedemType, true, out constructor))
{
itemType = generILisreplacedemType;
return true;
}
}
if (isImplGenerICollec)
{
if (TryGetConstructorInfo(t, generICollectionItemType, true, out constructor))
{
itemType = generICollectionItemType;
return true;
}
}
if (isImplGenerIEnumerable && isImplICollection)
{
if (TryGetConstructorInfo(t, generIEnumerableItemType, false, out constructor))
{
itemType = generIEnumerableItemType;
return true;
}
}
if (IsImplIList)
{
if (TryGetConstructorInfo(t, typeof(object), true, out constructor))
{
itemType = typeof(object);
return true;
}
}
if (isImplICollection)
{
if (TryGetConstructorInfo(t, typeof(object), false, out constructor))
{
itemType = typeof(object);
return true;
}
}
return false;
}
19
Source : IDictionaryResolver.cs
with MIT License
from 1996v
with MIT License
from 1996v
internal static bool TypeIsDictionary(Type t, out ConstructorInfo constructor, out bool typeIsGeneric, out Type genericTypeDefinition, out Type genericKeyType, out Type genericValueType)
{
constructor = null;
typeIsGeneric = false;
genericKeyType = null;
genericValueType = null;
genericTypeDefinition = null;
Type genericType = null;
bool hasIDictionaryGeneric = false;
bool hasIDictionary = false;
if (t.IsInterface)
{
if (t == typeof(IDictionary))
{
return true;
}
if (t.IsGenericType)
{
genericTypeDefinition = t.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IDictionary<,>) || genericTypeDefinition == typeof(IReadOnlyDictionary<,>))
{
Type[] args = t.GetGenericArguments();
typeIsGeneric = true;
genericType = t;
genericKeyType = args[0];
genericValueType = args[1];
return true;
}
}
return false;
}
if (t.IsGenericType)
{
genericTypeDefinition = t.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Dictionary<,>) ||
genericTypeDefinition == typeof(SortedList<,>))
{
constructor = t.GetAppointTypeCtor(typeof(int));
typeIsGeneric = true;
Type[] args = t.GetGenericArguments();
genericKeyType = args[0];
genericValueType = args[1];
return true;
}
}
IEnumerable<Type> intserfaces = t.GetInterfaces();
foreach (Type item in intserfaces)
{
if (item.IsGenericType)
{
genericTypeDefinition = item.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IDictionary<,>) ||
genericTypeDefinition == typeof(IReadOnlyDictionary<,>))
{
genericType = item;
Type[] args = item.GetGenericArguments();
genericKeyType = args[0];
genericValueType = args[1];
hasIDictionaryGeneric = true;
break;
}
}
else if (item == typeof(IDictionary))
{
hasIDictionary = true;
}
}
if (hasIDictionaryGeneric)
{
typeIsGeneric = true;
//clreplaced <T>:IDictionary<int,int>
// ctor( ReadOnlyDic<,> )
// ctor( Dictionary<,> )
if (TryGetConstructorInfo(t, genericKeyType, genericValueType, true, out constructor))
{
return true;
}
}
else if (hasIDictionary)
{
constructor = t.GetDefaultNoArgCtorOrAppointTypeCtor(typeof(IDictionary));
if (constructor != null)
{
return true;
}
}
return false;
}
19
Source : ValueMember.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType)
{
dictionaryType = keyType = valueType = null;
try
{
#if WINRT || COREFX || PROFILE259
var info = memberType.GetTypeInfo();
#else
var info = memberType;
#endif
MethodInfo b, a, ar, f;
if(ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out b, out a, out ar, out f))
{
return false;
}
if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
#if PROFILE259
var typeArgs = memberType.GetGenericTypeDefinition().GenericTypeArguments;
#else
var typeArgs = memberType.GetGenericArguments();
#endif
if (IsValidMapKeyType(typeArgs[0]))
{
keyType = typeArgs[0];
valueType = typeArgs[1];
dictionaryType = memberType;
}
return false;
}
#if PROFILE259
foreach (var iType in memberType.GetTypeInfo().ImplementedInterfaces)
#else
foreach (var iType in memberType.GetInterfaces())
#endif
{
#if WINRT || COREFX || PROFILE259
info = iType.GetTypeInfo();
#else
info = iType;
#endif
if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName);
#if PROFILE259
var typeArgs = iType.GetGenericTypeDefinition().GenericTypeArguments;
#else
var typeArgs = iType.GetGenericArguments();
#endif
if (IsValidMapKeyType(typeArgs[0]))
{
keyType = typeArgs[0];
valueType = typeArgs[1];
dictionaryType = memberType;
}
}
}
if (dictionaryType == null) return false;
// (note we checked the key type already)
// not a map if value is repeated
Type itemType = null, defaultType = null;
model.ResolveListTypes(valueType, ref itemType, ref defaultType);
if (itemType != null) return false;
return dictionaryType != null;
}
catch
{
// if it isn't a good fit; don't use "map"
return false;
}
}
19
Source : ImmutableCollectionDecorator.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
static Type ResolveIReadOnlyCollection(Type declaredType, Type t)
{
#if WINRT || COREFX || PROFILE259
foreach (Type intImplBasic in declaredType.GetTypeInfo().ImplementedInterfaces)
{
TypeInfo intImpl = intImplBasic.GetTypeInfo();
if (intImpl.IsGenericType && intImpl.Name.StartsWith("IReadOnlyCollection`"))
{
if(t != null)
{
Type[] typeArgs = intImpl.GenericTypeArguments;
if (typeArgs.Length != 1 && typeArgs[0] != t) continue;
}
return intImplBasic;
}
}
#else
foreach (Type intImpl in declaredType.GetInterfaces())
{
if (intImpl.IsGenericType && intImpl.Name.StartsWith("IReadOnlyCollection`"))
{
if(t != null)
{
Type[] typeArgs = intImpl.GetGenericArguments();
if (typeArgs.Length != 1 && typeArgs[0] != t) continue;
}
return intImpl;
}
}
#endif
return null;
}
19
Source : ServiceCollectionExtension.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public static void AutoRegister(this IServiceCollection services)
{
#region 自动注入
var allreplacedemblies = replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies().Select(replacedembly.Load);
foreach (var serviceAsm in allreplacedemblies)
{
var serviceList = serviceAsm.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && !t.IsInterface);
foreach (Type serviceType in serviceList.Where(t => typeof(IScoped).IsreplacedignableFrom(t)))
{
var interfaceTypes = serviceType.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
services.AddScoped(interfaceType, serviceType);
}
}
foreach (Type serviceType in serviceList.Where(t => typeof(ISingleton).IsreplacedignableFrom(t)))
{
var interfaceTypes = serviceType.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
services.AddSingleton(interfaceType, serviceType);
}
}
foreach (Type serviceType in serviceList.Where(t => typeof(ITransient).IsreplacedignableFrom(t)))
{
var interfaceTypes = serviceType.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
services.AddTransient(interfaceType, serviceType);
}
}
foreach (Type serviceType in serviceList.Where(t => t.IsSubclreplacedOf(typeof(BackgroundService))))
{
services.AddTransient(typeof(IHostedService), serviceType);
}
}
#endregion
}
19
Source : TypeExtensions.cs
with MIT License
from a34546
with MIT License
from a34546
public static bool HasImplementedRawGeneric(this Type type, Type generic)
{
if (type == null) throw new ArgumentNullException(nameof(type));
if (generic == null) throw new ArgumentNullException(nameof(generic));
var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
if (isTheRawGenericType) return true;
while (type != null && type != typeof(object))
{
isTheRawGenericType = IsTheRawGenericType(type);
if (isTheRawGenericType) return true;
type = type.BaseType;
}
return false;
bool IsTheRawGenericType(Type test)
=> generic == (test.IsGenericType ? test.GetGenericTypeDefinition() : test);
}
19
Source : VxHelpers.cs
with MIT License
from Aaltuj
with MIT License
from Aaltuj
internal static bool TypeImplementsInterface(Type type, Type typeToImplement)
{
Type foundInterface = type
.GetInterfaces()
.Where(i =>
{
return i.Name == typeToImplement.Name;
})
.Select(i => i)
.FirstOrDefault();
return foundInterface != null;
}
19
Source : Program.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public async Task RunBotAsync(string botToken)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
_discordClient = new DiscordSocketClient();
_commands = new CommandService();
var optionsBuilder = new DbContextOptionsBuilder<BotDataContext>();
var options = optionsBuilder
.UseSqlite(PathToDb)
.Options;
var services = new ServiceCollection()
.AddSingleton<DiscordSocketClient>(_discordClient)
.AddSingleton<ApplicationContext>()
.AddSingleton<BotDataContext>(new BotDataContext(options))
.AddSingleton<CommandService>(_commands)
.AddSingleton<OCUserRepository>()
.AddSingleton<Chanel2ServerRepository>()
.AddSingleton<DiscordManager>()
.AddSingleton<IRepository<OCUser>>(x => x.GetService<OCUserRepository>())
.AddSingleton<IRepository<Chanel2Server>>(x => x.GetService<Chanel2ServerRepository>());
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!type.IsClreplaced)
{
continue;
}
if (type.GetInterfaces().Any(x => x == typeof(ICommand)))
{
services.AddSingleton(type);
}
}
_services = services
.AddSingleton<Listener>()
.BuildServiceProvider();
_discordClient.Log += _discordClient_Log;
_discordClient.ChannelDestroyed += _discordClient_ChannelDestroyed;
await RegisterCommandAsync();
await _discordClient.LoginAsync(Discord.TokenType.Bot, botToken);
await _discordClient.StartAsync();
var listener = _services.GetService<Listener>();
const int WAIT_LOGIN_DISCORD_TIME = 5000;
const int REFRESH_TIME = 5000;
var t = new System.Threading.Timer((a) => { listener.UpdateChats(); }, null, WAIT_LOGIN_DISCORD_TIME, REFRESH_TIME);
await Task.Delay(-1);
}
19
Source : Service.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void DependencyInjection()
{
//may better way use a native .Net Core DI
var d = new Dictionary<int, IGenerateResponseContainer>();
foreach (var type in replacedembly.GetEntryreplacedembly().GetTypes())
{
if (!type.IsClreplaced)
{
continue;
}
if (type.GetInterfaces().Any(x => x == typeof(IGenerateResponseContainer)))
{
var t = (IGenerateResponseContainer)Activator.CreateInstance(type);
d[t.RequestTypePackage] = t;
}
}
ServiceDictionary = d;
}
19
Source : ImplementsAttribute.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public override bool IsConstraintSatisfied(Type type)
{
if (base.IsConstraintSatisfied(type))
{
var interfaces = type.GetInterfaces();
for (var i = 0; i < interfaces.Length; i++)
{
if (interfaces[i] == InterfaceType)
{
return true;
}
}
}
return false;
}
19
Source : ServiceFacadeInspector.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void DrawSceneGUI(SceneView sceneView)
{
if (!MixedRealityToolkit.IsInitialized || !MixedRealityToolkit.Instance.HasActiveProfile)
{
return;
}
InitializeServiceInspectorLookup();
foreach (KeyValuePair<Type, Type> inspectorTypePair in inspectorTypeLookup)
{
// Find the facade replacedociated with this service
ServiceFacade facade;
// If no facade exists for this service type, move on
if (!ServiceFacade.FacadeServiceLookup.TryGetValue(inspectorTypePair.Key, out facade) || facade.Destroyed || facade == null)
{
continue;
}
foreach (Type interfaceType in inspectorTypePair.Key.GetInterfaces())
{
IMixedRealityServiceInspector inspectorInstance;
if (!GetServiceInspectorInstance(interfaceType, out inspectorInstance))
{
continue;
}
if (Selection.Contains(facade) || inspectorInstance.AlwaysDrawSceneGUI)
{
inspectorInstance.DrawSceneGUI(facade.Service, sceneView);
}
}
}
}
19
Source : ServiceFacadeInspector.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private bool DrawProfile(Type serviceType)
{
bool drawProfileField = true;
foreach (Type interfaceType in serviceType.GetInterfaces())
{
IMixedRealityServiceInspector inspectorInstance;
if (GetServiceInspectorInstance(interfaceType, out inspectorInstance))
{
drawProfileField &= inspectorInstance.DrawProfileField;
}
}
if (!drawProfileField)
{ // We've been instructed to skip drawing a profile by the inspector
return false;
}
bool foundAndDrewProfile = false;
// Draw the base profile stuff
if (typeof(BaseCoreSystem).IsreplacedignableFrom(serviceType))
{
SerializedObject activeProfileObject = new SerializedObject(MixedRealityToolkit.Instance.ActiveProfile);
// Would be nice to handle this using some other method
// Would be nice to handle this with a lookup instead
if (typeof(IMixedRealityInputSystem).IsreplacedignableFrom(serviceType))
{
SerializedProperty serviceProfileProp = activeProfileObject.FindProperty("inputSystemProfile");
BaseMixedRealityProfileInspector.RenderReadOnlyProfile(serviceProfileProp);
EditorGUILayout.Space();
foundAndDrewProfile = true;
}
else if (typeof(IMixedRealityBoundarySystem).IsreplacedignableFrom(serviceType))
{
SerializedProperty serviceProfileProp = activeProfileObject.FindProperty("boundaryVisualizationProfile");
BaseMixedRealityProfileInspector.RenderReadOnlyProfile(serviceProfileProp);
EditorGUILayout.Space();
foundAndDrewProfile = true;
}
else if (typeof(IMixedRealityDiagnosticsSystem).IsreplacedignableFrom(serviceType))
{
SerializedProperty serviceProfileProp = activeProfileObject.FindProperty("diagnosticsSystemProfile");
BaseMixedRealityProfileInspector.RenderReadOnlyProfile(serviceProfileProp);
EditorGUILayout.Space();
foundAndDrewProfile = true;
}
else if (typeof(IMixedRealitySpatialAwarenessSystem).IsreplacedignableFrom(serviceType))
{
SerializedProperty serviceProfileProp = activeProfileObject.FindProperty("spatialAwarenessSystemProfile");
BaseMixedRealityProfileInspector.RenderReadOnlyProfile(serviceProfileProp);
EditorGUILayout.Space();
foundAndDrewProfile = true;
}
else if (typeof(IMixedRealityCameraSystem).IsreplacedignableFrom(serviceType))
{
SerializedProperty serviceProfileProp = activeProfileObject.FindProperty("cameraProfile");
BaseMixedRealityProfileInspector.RenderReadOnlyProfile(serviceProfileProp);
EditorGUILayout.Space();
foundAndDrewProfile = true;
}
else if (typeof(IMixedRealitySceneSystem).IsreplacedignableFrom(serviceType))
{
SerializedProperty serviceProfileProp = activeProfileObject.FindProperty("sceneSystemProfile");
BaseMixedRealityProfileInspector.RenderReadOnlyProfile(serviceProfileProp);
EditorGUILayout.Space();
foundAndDrewProfile = true;
}
}
else if (typeof(BaseExtensionService).IsreplacedignableFrom(serviceType))
{
// Make sure the extension service profile isn't null
if (MixedRealityToolkit.Instance.ActiveProfile.RegisteredServiceProvidersProfile != null)
{
// If this is an extension service, see if it uses a profile
MixedRealityServiceConfiguration[] serviceConfigs = MixedRealityToolkit.Instance.ActiveProfile.RegisteredServiceProvidersProfile.Configurations;
for (int serviceIndex = 0; serviceIndex < serviceConfigs.Length; serviceIndex++)
{
MixedRealityServiceConfiguration serviceConfig = serviceConfigs[serviceIndex];
if (serviceConfig.ComponentType.Type.IsreplacedignableFrom(serviceType) && serviceConfig.Profile != null)
{
// We found the service that this type uses - draw the profile
SerializedObject serviceConfigObject = new SerializedObject(MixedRealityToolkit.Instance.ActiveProfile.RegisteredServiceProvidersProfile);
SerializedProperty serviceConfigArray = serviceConfigObject.FindProperty("configurations");
SerializedProperty serviceConfigProp = serviceConfigArray.GetArrayElementAtIndex(serviceIndex);
SerializedProperty serviceProfileProp = serviceConfigProp.FindPropertyRelative("configurationProfile");
BaseMixedRealityProfileInspector.RenderReadOnlyProfile(serviceProfileProp);
EditorGUILayout.Space();
foundAndDrewProfile = true;
break;
}
}
}
}
return foundAndDrewProfile;
}
19
Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private void TraverseEventSystemHandlerHierarchy<T>(IEventSystemHandler handler, Action<Type, IEventSystemHandler> func) where T : IEventSystemHandler
{
using (TraverseEventSystemHandlerHierarchyPerfMarker.Auto())
{
var handlerType = typeof(T);
// Need to call on handlerType first, because GetInterfaces below will only return parent types.
func(handlerType, handler);
foreach (var iface in handlerType.GetInterfaces())
{
if (!iface.Equals(eventSystemHandlerType))
{
func(iface, handler);
}
}
}
}
19
Source : GenericInterface.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static IGenericInterface AsGenericInterface(this object @this, Type type)
{
var interfaceType = (
from @interface in @this.GetType().GetInterfaces()
where @interface.IsGenericType
let definition = @interface.GetGenericTypeDefinition()
where definition == type
select @interface
)
.SingleOrDefault();
return interfaceType != null
? new GenericInterfaceImpl(@this, interfaceType)
: null;
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterTransientDependency()
{
//虚函数
var virtualClreplaced = replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced && t.GetInterfaces().Length == 0)).ToList();
var virtualMethods = virtualClreplaced.SelectMany(d => d.GetMethods()).Where(d =>
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopPublisherAttribute)) ||
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopSubscriberAttribute))).ToList();
var methods = TypeFinder.FindAllInterface(replacedemblies).SelectMany(d => d.GetMethods()).ToList();
methods.AddRange(virtualMethods);
var publishers = methods.SelectMany(d => d.GetCustomAttributes<AopPublisherAttribute>()).ToList();
var check = publishers.Select(d => d.Channel).GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).Where(d => d.Value > 1).ToList();
if (check.Any())
{
throw new Exception($"[AopCache AopPublisherAttribute] [Key 重复:{string.Join("、", check.Select(d => d.Key))}]");
}
//开启发布
if (publishers.Any())
{
AopPublisherAttribute.Enable = true;
}
var existsList = methods.Where(d =>
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopPublisherAttribute)) &&
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopCacheAttribute))).ToList();
if (existsList.Any())
{
throw new Exception($"[AopCache AopPublisherAttribute] [不能与 AopCacheAttribute 一起使用 :{string.Join("、", existsList.Select(d => $"{d.DeclaringType?.FullName}.{d.Name}"))}]");
}
var subscribers = methods.SelectMany(d => d.GetCustomAttributes<AopSubscriberAttribute>()).ToList();
if (subscribers.Any())
{
AopSubscriberAttribute.ChannelList = subscribers.Select(d => d.Channel).Distinct().ToList();
AopSubscriberAttribute.MethodList = methods.Where(d =>
d.CustomAttributes != null &&
d.CustomAttributes.Any(c => c.AttributeType.Name == nameof(AopSubscriberAttribute))).ToList();
foreach (var subscriber in subscribers)
{
if (string.IsNullOrWhiteSpace(subscriber.Map))
continue;
//特殊处理冒号,兼容冒号
subscriber.Map = subscriber.Map.Replace(":", ".");
var key = subscriber.GetMapDictionaryKey();
if (AopSubscriberAttribute.MapDictionary.ContainsKey(key))
continue;
var mapDic = subscriber.Map.Split(',')
.Where(d => d.IndexOf('=') > -1
&& !string.IsNullOrWhiteSpace(d.Split('=')[0])
&& !string.IsNullOrWhiteSpace(d.Split('=')[1]))
.ToDictionary(d => d.Split('=')[0].Trim(), d => d.Split('=')[1].Trim().TrimStart('{').TrimEnd('}'));
AopSubscriberAttribute.MapDictionary.TryAdd(key, mapDic);
}
}
}
19
Source : Serializer.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
public object TryDeserializeObject(object serialized, Type requestedType, object deserializationContext)
{
if (requestedType is not null)
{
if (requestedType.IsEnum)
{
return Enum.ToObject(requestedType, serialized);
}
}
Type deserializedType = serialized.GetType().GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ISerializedObject<>)).FirstOrDefault()?.GetGenericArguments()[0];
if (deserializedType is not null && Serializers.TryGetValue(deserializedType, out object serializer))
{
return typeof(IObjectSerializer<>).MakeGenericType(deserializedType).GetMethod(nameof(IObjectSerializer<object>.DeSerialize)).Invoke(serializer, new object[] { serialized, this, deserializationContext });
}
if (requestedType is not null)
{
}
return serialized;
}
19
Source : LaminarValueFactory.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
private ITypeDefinitionProvider GetProvider(object value)
{
if (value is ITypeDefinitionProvider typeDefinitionProvider)
{
return typeDefinitionProvider;
}
if (value.GetType().IsGenericType && value.GetType().GetInterfaces().Where(x => x.IsGenericType).Select(x => x.GetGenericTypeDefinition()).Contains(typeof(ITypeDefinitionConstructor<>)))
{
value = ((dynamic)value).Construct();
}
if (value is ITypeDefinition typeDefinition)
{
IManualTypeDefinitionProvider manager = _factory.GetImplementation<IManualTypeDefinitionProvider>();
manager.RegisterTypeDefinition(typeDefinition);
return manager;
}
if (value is Type type)
{
IRigidTypeDefinitionManager manager = _factory.GetImplementation<IRigidTypeDefinitionManager>();
manager.SetType(type);
return manager;
}
IRigidTypeDefinitionManager rigidTypeDefinitionManager = _factory.GetImplementation<IRigidTypeDefinitionManager>();
rigidTypeDefinitionManager.SetTypeDefinition(value, null, null);
return rigidTypeDefinitionManager;
}
19
Source : Serializer.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
private void InitializeDictionaries()
{
foreach (Type type in typeof(Serializer).replacedembly.GetTypes())
{
Type serializerType = type.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IObjectSerializer<>)).FirstOrDefault();
if (serializerType is not null)
{
object serializer = _factory.CreateInstance(type);
Type genericParameter = serializerType.GetGenericArguments().FirstOrDefault();
Serializers.Add(genericParameter, serializer);
}
}
}
19
Source : ObjectFactory.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
private void RegisterImplementationUnsafe(Type interfaceType, Type implementationType)
{
Type[] interfaces = implementationType.GetInterfaces();
if (!(implementationType.GetInterfaces().Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == interfaceType)) && implementationType.IsClreplaced))
{
throw new ArgumentException($"Type {implementationType} is not a clreplaced that inherits from {interfaceType}");
}
_interfaceImplementations.Add(interfaceType, implementationType);
}
19
Source : MessageHandlerContainer.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
public void Register(Action<MessageHandlerMetadata>? configureMessageHandlerMetadata, params replacedembly[] replacedemblies)
{
var messageHandlerTypes = replacedemblies.SelectMany(a => a.GetTypes())
.Where(t => t.IsClreplaced && !t.IsAbstract)
.SelectMany(t => t.GetInterfaces())
.Where(i => typeof(IMessageHandler) == i)
.ToList();
foreach (Type messageHandlerType in messageHandlerTypes)
{
Register(messageHandlerType, configureMessageHandlerMetadata);
}
}
19
Source : MessageHandlerContainer.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
private static List<Type> GetPayloadTypes(Type messageHandlerType)
{
List<Type> payloadTypes = new List<Type>();
foreach (Type interfaceType in messageHandlerType.GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == typeof(IMessageHandler<>))
{
payloadTypes.Add(interfaceType.GetGenericArguments()[0]);
}
}
return payloadTypes.Distinct().ToList();
}
19
Source : DependencyInjectionMessageHandlerContainer.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
public void Register(Action<MessageHandlerMetadata>? configureMessageHandlerMetadata, params replacedembly[] replacedemblies)
{
var messageHandlerTypes = replacedemblies.SelectMany(a => a.GetTypes())
.Where(t => t.IsClreplaced && !t.IsAbstract && t.GetInterfaces().Contains(typeof(IMessageHandler)))
.ToList();
foreach (Type messageHandlerType in messageHandlerTypes)
{
Register(messageHandlerType, configureMessageHandlerMetadata);
}
}
19
Source : AElfDefaultConventionalRegistrar.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
protected override ServiceLifetime? GetServiceLifetimeFromClreplacedHierarcy(Type type)
{
//Get ABP lifetime from ABP interface, ITransientDependency,ISingletonDependency or IScopedDependency
var lifeTime = base.GetServiceLifetimeFromClreplacedHierarcy(type);
if (lifeTime != null)
{
return null;
}
//if no lifetime interface was found, try to get clreplaced with the same interface,
//HelloService -> IHelloService
//HelloManager -> IHelloManager
var interfaceName = "I" + type.Name;
if (type.GetInterfaces().Any(p => p.Name == interfaceName))
{
if (_transientTypeSuffixes.Any(suffix => type.Name.EndsWith(suffix)))
{
return ServiceLifetime.Transient;
}
}
return null;
}
19
Source : RegistrationContext.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
private static bool IsreplacedignableToGenericType(Type givenType, Type genericType)
{
var interfaceTypes = givenType.GetInterfaces();
if (interfaceTypes.Any(it => it.IsGenericType && it.GetGenericTypeDefinition() == genericType))
{
return true;
}
if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
return true;
var baseType = givenType.BaseType;
return baseType != null && IsreplacedignableToGenericType(baseType, genericType);
}
19
Source : StoredProcHelper.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
public static void SetTypeMap(IEnumerable<Type> spTypes)
{
var spInterfaces = new[] { typeof(IStoredProc<>), typeof(IStoredProc<,>) };
var dbTypes = spTypes
.SelectMany(x => x.GetInterfaces())
.Where(x => x.IsGenericType)
.Where(x =>
{
var typeDef = x.GetGenericTypeDefinition();
return spInterfaces.Any(sp => typeDef == sp);
})
.SelectMany(x => x.GetGenericArguments());
foreach (var modelType in dbTypes)
{
SqlMapper.SetTypeMap(modelType, CreateMap(modelType));
}
}
19
Source : ContainerAttributeUtils.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
private static IEnumerable<Type> GetBaseTypes(Type type)
{
foreach (var i in type.GetInterfaces().Where(IsRationalForRegistration))
{
yield return i;
}
var baseType = type.BaseType;
while (baseType != null && IsRationalForRegistration(baseType))
{
yield return baseType;
baseType = baseType.BaseType;
}
}
19
Source : ReflectionUtils.cs
with MIT License
from aillieo
with MIT License
from aillieo
public static IEnumerable<Type> FindImplementations(Type interfaceType, bool interfaceIsGenericType)
{
if (interfaceIsGenericType)
{
return AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(a => a.GetTypes()
.Where(t => t.GetInterfaces()
.Any(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == interfaceType)));
}
else
{
return AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(a => a.GetTypes()
.Where(t => t.GetInterfaces().Contains(interfaceType)));
}
}
19
Source : BotExtends.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private static IEnumerable<Type> ScanHandler()
{
var handlers = replacedembly
.GetExecutingreplacedembly()
.GetTypes()
.Where(t => !t.IsInterface)
.Where(t => t.GetInterfaces().Any(i => i.Name.StartsWith(nameof(ICommandHandler<BotBase>))));
return handlers;
}
19
Source : Extends.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private static void AddScanned(
Type service,
Type condition,
Action<Type, Type> abstractImplementation,
Action<Type> realisticImplementation,
IServiceCollection services,
params Type[] abstracts)
{
if (!service.GetInterfaces().Contains(condition))
{
return;
}
foreach (var inputInterface in abstracts.Where(t => t.IsInterface))
{
if (service.GetInterfaces().Any(t => t == inputInterface))
{
if (!services.Any(t => t.ServiceType == service && t.ImplementationType == inputInterface))
{
abstractImplementation(inputInterface, service);
Console.WriteLine($"Service:\t{service.Name}\t\t{service.replacedembly.FullName?.Split(',')[0]}\t\tsuccess as\t{inputInterface.Name}");
}
}
}
foreach (var inputAbstractClreplaced in abstracts.Where(t => t.IsAbstract))
{
if (service.IsSubclreplacedOf(inputAbstractClreplaced))
{
if (!services.Any(t => t.ServiceType == service && t.ImplementationType == inputAbstractClreplaced))
{
abstractImplementation(inputAbstractClreplaced, service);
Console.WriteLine($"Service:\t{service.Name}\t\t{service.replacedembly.FullName?.Split(',')[0]}\t\tsuccess as\t{inputAbstractClreplaced.Name}");
}
}
}
if (!services.Any(t => t.ServiceType == service && t.ImplementationType == service))
{
realisticImplementation(service);
Console.WriteLine($"Service:\t{service.Name}\t\t{service.replacedembly.FullName?.Split(',')[0]}\t\tsuccess");
}
}
19
Source : InstranceMaker.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
public static object Make(this Type type)
{
if (type == typeof(string))
{
return "an example string.";
}
else if (type == typeof(int) || type == typeof(int?))
{
return 0;
}
else if (type == typeof(DateTime) || type == typeof(DateTime?))
{
return DateTime.UtcNow;
}
else if (type == typeof(Guid) || type == typeof(Guid?))
{
return Guid.NewGuid();
}
else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
{
return DateTimeOffset.UtcNow;
}
else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?))
{
return TimeSpan.FromMinutes(37);
}
else if (type == typeof(bool) || type == typeof(bool?))
{
return true;
}
// List
else if (type.IsGenericType && type.GetGenericTypeDefinition().GetInterfaces().Any(t => t.IsreplacedignableFrom(typeof(IEnumerable))))
{
var itemType = type.GetGenericArguments()[0];
return GetArrayWithInstanceInherts(itemType);
}
// Array
else if (type.GetInterface(typeof(IEnumerable<>).FullName ?? string.Empty) != null)
{
var itemType = type.GetElementType();
var list = GetArrayWithInstanceInherts(itemType);
var array = Array.CreateInstance(itemType ?? typeof(string[]), list.Count);
list.CopyTo(array, 0);
return array;
}
else
{
var instance = GenerateWithConstructor(type);
if (instance != null)
{
foreach (var property in instance.GetType().GetProperties())
{
if (property.CustomAttributes.Any(t => t.AttributeType == typeof(JsonIgnoreAttribute)))
{
property.SetValue(instance, null);
}
else if (property.CustomAttributes.Any(t => t.AttributeType == typeof(InstanceMakerIgnore)))
{
property.SetValue(instance, null);
}
else if (property.SetMethod != null)
{
property.SetValue(instance, Make(property.PropertyType));
}
}
}
return instance;
}
}
19
Source : JsonTypeReflector.cs
with MIT License
from akaskela
with MIT License
from akaskela
private static T GetAttribute<T>(Type type) where T : Attribute
{
T attribute;
#if !(NET20 || DOTNET)
Type metadataType = GetreplacedociatedMetadataType(type);
if (metadataType != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataType, true);
if (attribute != null)
{
return attribute;
}
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(type, true);
if (attribute != null)
{
return attribute;
}
foreach (Type typeInterface in type.GetInterfaces())
{
attribute = ReflectionUtils.GetAttribute<T>(typeInterface, true);
if (attribute != null)
{
return attribute;
}
}
return null;
}
19
Source : JsonTypeReflector.cs
with MIT License
from akaskela
with MIT License
from akaskela
private static T GetAttribute<T>(MemberInfo memberInfo) where T : Attribute
{
T attribute;
#if !(NET20 || DOTNET)
Type metadataType = GetreplacedociatedMetadataType(memberInfo.DeclaringType);
if (metadataType != null)
{
MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo);
if (metadataTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true);
if (attribute != null)
{
return attribute;
}
}
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(memberInfo, true);
if (attribute != null)
{
return attribute;
}
if (memberInfo.DeclaringType != null)
{
foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces())
{
MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo);
if (interfaceTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(interfaceTypeMemberInfo, true);
if (attribute != null)
{
return attribute;
}
}
}
}
return null;
}
19
Source : ReflectionUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, nameof(targetType));
List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr));
// GetProperties on an interface doesn't return properties from its interfaces
if (targetType.IsInterface())
{
foreach (Type i in targetType.GetInterfaces())
{
propertyInfos.AddRange(i.GetProperties(bindingAttr));
}
}
GetChildPrivateProperties(propertyInfos, targetType, bindingAttr);
// a base clreplaced private getter/setter will be inaccessable unless the property was gotten from the base clreplaced
for (int i = 0; i < propertyInfos.Count; i++)
{
PropertyInfo member = propertyInfos[i];
if (member.DeclaringType != targetType)
{
PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member);
propertyInfos[i] = declaredMember;
}
}
return propertyInfos;
}
19
Source : TypeExtensions.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static bool replacedignableToTypeName(this Type type, string fullTypeName, out Type match)
{
Type current = type;
while (current != null)
{
if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal))
{
match = current;
return true;
}
current = current.BaseType();
}
foreach (Type i in type.GetInterfaces())
{
if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal))
{
match = type;
return true;
}
}
match = null;
return false;
}
19
Source : TypeExtensions.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static bool ImplementInterface(this Type type, Type interfaceType)
{
for (Type currentType = type; currentType != null; currentType = currentType.BaseType())
{
IEnumerable<Type> interfaces = currentType.GetInterfaces();
foreach (Type i in interfaces)
{
if (i == interfaceType || (i != null && i.ImplementInterface(interfaceType)))
{
return true;
}
}
}
return false;
}
19
Source : ReflectionUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition));
if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition())
{
throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition));
}
if (type.IsInterface())
{
if (type.IsGenericType())
{
Type interfaceDefinition = type.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = type;
return true;
}
}
}
foreach (Type i in type.GetInterfaces())
{
if (i.IsGenericType())
{
Type interfaceDefinition = i.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = i;
return true;
}
}
}
implementingType = null;
return false;
}
19
Source : Uncapsulator.cs
with MIT License
from albahari
with MIT License
from albahari
IEnumerable<Type> GetTypeHierarchy (Type type) =>
type.IsInterface ? type.GetInterfaces ().Prepend (type) :
_options.PublicOnly ? new[] { type } :
Descend (type, (t => t.BaseType));
19
Source : MicroSplatShaderGUI_Compiler.cs
with MIT License
from alelievr
with MIT License
from alelievr
public void Init()
{
if (terrainBody == null || extensions.Count == 0)
{
string[] paths = replacedetDatabase.Findreplacedets("microsplat_ t:Textreplacedet");
for (int i = 0; i < paths.Length; ++i)
{
paths[i] = replacedetDatabase.GUIDToreplacedetPath(paths[i]);
}
for (int i = 0; i < paths.Length; ++i)
{
var p = paths[i];
if (p.EndsWith("microsplat_terrain_body.txt"))
{
terrainBody = replacedetDatabase.LoadreplacedetAtPath<Textreplacedet>(p);
}
if (p.EndsWith("microsplat_shared.txt"))
{
sharedInc = replacedetDatabase.LoadreplacedetAtPath<Textreplacedet>(p);
}
}
// init extensions
var types = System.Reflection.replacedembly.GetExecutingreplacedembly().GetTypes();
var possible = (from System.Type type in types
where type.IsSubclreplacedOf(typeof(FeatureDescriptor))
select type).ToArray();
for (int i = 0; i < possible.Length; ++i)
{
var typ = possible[i];
FeatureDescriptor ext = System.Activator.CreateInstance(typ) as FeatureDescriptor;
ext.InitCompiler(paths);
extensions.Add(ext);
}
extensions.Sort(delegate(FeatureDescriptor p1, FeatureDescriptor p2)
{
if (p1.DisplaySortOrder() != 0 || p2.DisplaySortOrder() != 0)
{
return p1.DisplaySortOrder().CompareTo(p2.DisplaySortOrder());
}
return p1.GetType().Name.CompareTo(p2.GetType().Name);
});
var adapters = (from System.Type type in types
where(type.GetInterfaces().Contains(typeof(IRenderLoopAdapter)))
select type).ToArray();
availableRenderLoops.Clear();
for (int i = 0; i < adapters.Length; ++i)
{
var typ = adapters[i];
IRenderLoopAdapter adapter = System.Activator.CreateInstance(typ) as IRenderLoopAdapter;
adapter.Init(paths);
availableRenderLoops.Add(adapter);
}
}
}
19
Source : ObjectMapps.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public ObjectMapps<T> HasRule<Source>()
{
if (typeof(Source).GetInterfaces().Length <= 0 || !typeof(Source).GetInterfaces().Any(x => x.ToString().Contains("IDbRuleTrigger") && x.FullName.Contains(typeof(T).FullName)))
throw new EnreplacedyException($"Source dose not implement interface IDbRuleTrigger<{typeof(T).Name }>");
var rule = typeof(Source).CreateInstance();
DbSchema.CachedIDbRuleTrigger.GetOrAdd(typeof(T), rule);
return this;
}
19
Source : TypeMapps.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public TypeMapps HasRule(Type ruleType)
{
if (ruleType.GetInterfaces().Length <= 0 || !ruleType.GetInterfaces().Any(x => x.ToString().Contains("IDbRuleTrigger") && x.ToString().Contains(ruleType.FullName)))
throw new EnreplacedyException($"ruleType dose not implement interface IDbRuleTrigger<{ruleType.Name }>");
var rule = ruleType.CreateInstance();
DbSchema.CachedIDbRuleTrigger.GetOrAdd(ruleType, rule);
return this;
}
19
Source : TypeHelper.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public static Type FindIEnumerable(Type seqType)
{
if (seqType == null || seqType == typeof(string))
return null;
if (seqType.IsArray)
return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
if (seqType.IsGenericType)
{
foreach (Type arg in seqType.GetGenericArguments())
{
Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
if (ienum.IsreplacedignableFrom(seqType))
{
return ienum;
}
}
}
Type[] ifaces = seqType.GetInterfaces();
if (ifaces != null && ifaces.Length > 0)
{
foreach (Type iface in ifaces)
{
Type ienum = FindIEnumerable(iface);
if (ienum != null) return ienum;
}
}
if (seqType.BaseType != null && seqType.BaseType != typeof(object))
{
return FindIEnumerable(seqType.BaseType);
}
return null;
}
19
Source : OpenEdgeCompositeMethodCallTranslator.cs
with Apache License 2.0
from alexwiese
with Apache License 2.0
from alexwiese
public static IEnumerable<Type> GetTranslatorMethods<TInteface>()
=> replacedembly
.GetExecutingreplacedembly()
.GetTypes().Where(t =>
t.GetInterfaces().Any(i => i == typeof(TInteface))
&& t.GetConstructors().Any(c => c.GetParameters().Length == 0));
19
Source : OpenApiSchemaExtensions.cs
with MIT License
from aliencube
with MIT License
from aliencube
[Obsolete("This method is now obsolete", error: true)]
public static Dictionary<string, OpenApiSchema> ToOpenApiSchemas(this Type type, NamingStrategy namingStrategy, OpenApiSchemaVisibilityAttribute attribute = null, bool returnSingleSchema = false, int depth = 0)
{
type.ThrowIfNullOrDefault();
var schema = (OpenApiSchema)null;
var schemeName = type.GetOpenApiTypeName(namingStrategy);
if (depth == 8)
{
schema = new OpenApiSchema()
{
Type = type.ToDataType(),
Format = type.ToDataFormat()
};
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
depth++;
if (type.IsJObjectType())
{
schema = typeof(object).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiNullable(out var unwrappedValueType))
{
schema = unwrappedValueType.ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
schema.Nullable = true;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
schema = new OpenApiSchema()
{
Type = type.ToDataType(),
Format = type.ToDataFormat()
};
if (!attribute.IsNullOrDefault())
{
var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());
schema.Extensions.Add("x-ms-visibility", visibility);
}
if (type.IsUnflaggedEnumType())
{
var converterAttribute = type.GetCustomAttribute<JsonConverterAttribute>();
if (!converterAttribute.IsNullOrDefault()
&& typeof(StringEnumConverter).IsreplacedignableFrom(converterAttribute.ConverterType))
{
var enums = type.ToOpenApiStringCollection(namingStrategy);
schema.Type = "string";
schema.Format = null;
schema.Enum = enums;
schema.Default = enums.First();
}
else
{
var enums = type.ToOpenApiIntegerCollection();
schema.Enum = enums;
schema.Default = enums.First();
}
}
if (type.IsSimpleType())
{
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiDictionary())
{
schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
if (type.IsOpenApiArray())
{
schema.Type = "array";
schema.Items = (type.GetElementType() ?? type.GetGenericArguments()[0]).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
}
var allProperties = type.IsInterface
? new[] { type }.Concat(type.GetInterfaces()).SelectMany(i => i.GetProperties())
: type.GetProperties();
var properties = allProperties.Where(p => !p.ExistsCustomAttribute<JsonIgnoreAttribute>());
var retVal = new Dictionary<string, OpenApiSchema>();
foreach (var property in properties)
{
var visiblity = property.GetCustomAttribute<OpenApiSchemaVisibilityAttribute>(inherit: false);
var propertyName = property.GetJsonPropertyName(namingStrategy);
var ts = property.DeclaringType.GetGenericArguments();
if (!ts.Any())
{
if (property.PropertyType.IsUnflaggedEnumType() && !returnSingleSchema)
{
var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var enumReference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiReferenceId(false, false)
};
var schema1 = new OpenApiSchema() { Reference = enumReference };
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
}
else if (property.PropertyType.IsSimpleType() || Nullable.GetUnderlyingType(property.PropertyType) != null || returnSingleSchema)
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else if (property.PropertyType.IsOpenApiDictionary())
{
var elementType = property.PropertyType.GetGenericArguments()[1];
if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else
{
var recur1 = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var elementReference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = elementType.GetOpenApiReferenceId(false, false)
};
var dictionarySchema = new OpenApiSchema()
{
Type = "object",
AdditionalProperties = new OpenApiSchema() { Reference = elementReference }
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
}
}
else if (property.PropertyType.IsOpenApiArray())
{
var elementType = property.PropertyType.GetElementType() ?? property.PropertyType.GetGenericArguments()[0];
if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
{
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
}
else
{
var elementReference = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(elementReference);
var reference1 = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = elementType.GetOpenApiReferenceId(false, false)
};
var arraySchema = new OpenApiSchema()
{
Type = "array",
Items = new OpenApiSchema()
{
Reference = reference1
}
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
}
}
else
{
var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
retVal.AddRange(recur1);
var reference1 = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiReferenceId(false, false)
};
var schema1 = new OpenApiSchema() { Reference = reference1 };
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
}
continue;
}
var reference = new OpenApiReference()
{
Type = ReferenceType.Schema,
Id = property.PropertyType.GetOpenApiRootReferenceId()
};
var referenceSchema = new OpenApiSchema() { Reference = reference };
if (!ts.Contains(property.PropertyType))
{
if (property.PropertyType.IsOpenApiDictionary())
{
reference.Id = property.PropertyType.GetOpenApiReferenceId(true, false);
var dictionarySchema = new OpenApiSchema()
{
Type = "object",
AdditionalProperties = referenceSchema
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
continue;
}
if (property.PropertyType.IsOpenApiArray())
{
reference.Id = property.PropertyType.GetOpenApiReferenceId(false, true);
var arraySchema = new OpenApiSchema()
{
Type = "array",
Items = referenceSchema
};
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
continue;
}
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
continue;
}
schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = referenceSchema;
}
retVal[schemeName] = schema;
return retVal;
}
19
Source : TypeExtensions.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static bool IsSameOrParent(Type parent, Type child)
{
if (parent == null) throw new ArgumentNullException("parent");
if (child == null) throw new ArgumentNullException("child");
if (parent == child ||
child.IsEnum && Enum.GetUnderlyingType(child) == parent ||
child.IsSubclreplacedOf(parent))
{
return true;
}
if (parent.IsInterface)
{
var interfaces = child.GetInterfaces();
foreach (var t in interfaces)
if (t == parent)
return true;
}
return false;
}
19
Source : ServiceAndRepositoryExtensions.cs
with MIT License
from alonsoalon
with MIT License
from alonsoalon
private static void RegsiterServices(this IServiceCollection services, IWebHostEnvironment env = null, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
var replacedemblyName = "AlonsoAdmin.Services";
// 根据程序集的名字获取程序集对象
replacedembly replacedembly = replacedembly.Load(replacedemblyName);//var replacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyName(new replacedemblyName(replacedemblyName));
//根据程序集的名字 获取程序集中所有的类型
IEnumerable<Type> types = replacedembly.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && t.FullName.EndsWith("Service"));
foreach (var implType in types)
{
var interfaceList = implType.GetInterfaces().Where(x => x.Name.EndsWith(implType.Name));
if (interfaceList.Any())
{
var interType = interfaceList.First();
ServiceDescriptor serviceDescriptor = new ServiceDescriptor(interType, implType, serviceLifetime);
services.Add(serviceDescriptor);
}
}
}
19
Source : ServiceAndRepositoryExtensions.cs
with MIT License
from alonsoalon
with MIT License
from alonsoalon
private static void RegsiterDomains(this IServiceCollection services, IWebHostEnvironment env = null, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped) {
var replacedemblyName = "AlonsoAdmin.Domain";
replacedembly replacedembly = replacedembly.Load(replacedemblyName);
//Type[] types = replacedembly.GetTypes();
//根据程序集的名字 获取程序集中Domain类
IEnumerable<Type> domianTypes = replacedembly.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && t.FullName.EndsWith("Domain"));
foreach (var implType in domianTypes)
{
var interfaceList = implType.GetInterfaces().Where(x => x.Name.EndsWith(implType.Name));
if (interfaceList.Any()) {
var interType = interfaceList.First();
ServiceDescriptor serviceDescriptor = new ServiceDescriptor(interType, implType, serviceLifetime);
services.Add(serviceDescriptor);
}
}
}
See More Examples