本文整理汇总了C#中System.Type.GetCustomAttribute方法的典型用法代码示例。如果您正苦于以下问题:C# Type.GetCustomAttribute方法的具体用法?C# Type.GetCustomAttribute怎么用?C# Type.GetCustomAttribute使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Type
的用法示例。
在下文中一共展示了Type.GetCustomAttribute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetEventSourceAttributeBuilder
/// <summary>
/// Copies the EventSourceAttribute from the interfaceType to a CustomAttributeBuilder.
/// </summary>
/// <param name="type">The interfaceType to copy.</param>
/// <returns>A CustomAttributeBuilder that can be assigned to a type.</returns>
internal static CustomAttributeBuilder GetEventSourceAttributeBuilder(Type type)
{
var attribute = type.GetCustomAttribute<EventSourceAttribute>() ?? new EventSourceAttribute();
var implementation = type.GetCustomAttribute<EventSourceImplementationAttribute>() ?? new EventSourceImplementationAttribute();
// by default, we will use a null guid, which will tell EventSource to generate the guid from the name
// but if we have already generated this type, we will have to generate a new one
string guid = implementation.Guid ?? attribute.Guid ?? null;
if (guid == null)
{
lock (_typesImplemented)
{
if (_typesImplemented.Contains(type))
guid = Guid.NewGuid().ToString();
else
_typesImplemented.Add(type);
}
}
var propertyValues = new object[]
{
implementation.Name ?? attribute.Name ?? (type.IsGenericType ? type.FullName : type.Name),
guid,
implementation.LocalizationResources ?? attribute.LocalizationResources ?? null
};
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(
_eventSourceAttributeConstructor,
_emptyParameters,
_eventSourceAttributePropertyInfo,
propertyValues);
return attributeBuilder;
}
示例2: GetMetadata
public FunctionMetadata GetMetadata(Type functionType)
{
FunctionMetadata functionMetadata = new FunctionMetadata(functionType);
functionMetadata.Id = MD5.GetHashString(functionType.FullName);
var displayNameAttr = functionType.GetCustomAttribute<DisplayNameAttribute>();
functionMetadata.DisplayName = displayNameAttr != null ? displayNameAttr.DisplayName : null;
var categoryAttr = functionType.GetCustomAttribute<CategoryAttribute>();
functionMetadata.Category = categoryAttr != null ? categoryAttr.Category : null;
var sectionAttr = functionType.GetCustomAttribute<SectionAttribute>();
functionMetadata.Section = sectionAttr != null ? sectionAttr.Name : null;
var descriptionAttr = functionType.GetCustomAttribute<DescriptionAttribute>();
functionMetadata.Description = descriptionAttr != null ? descriptionAttr.Description : null;
foreach (var signature in functionType.GetCustomAttributes<FunctionSignatureAttribute>())
{
functionMetadata.Signatures.Add(GetFunctionSignatureMetadata(signature));
}
foreach (var exampleUsage in functionType.GetCustomAttributes<ExampleUsageAttribute>())
{
functionMetadata.ExampleUsages.Add(new ExampleUsage(exampleUsage.Expression, exampleUsage.Result)
{
CanMultipleResults = exampleUsage.CanMultipleResults
});
}
return functionMetadata;
}
示例3: BuildResourceKey
internal static string BuildResourceKey(Type containerType, string propertyName, string separator = ".")
{
var modelAttribute = containerType.GetCustomAttribute<LocalizedModelAttribute>();
var pi = containerType.GetProperty(propertyName);
if(pi != null)
{
var propertyResourceKeyAttribute = pi.GetCustomAttribute<ResourceKeyAttribute>();
if(propertyResourceKeyAttribute != null)
{
// check if container type has resource key set
var prefix = string.Empty;
if(!string.IsNullOrEmpty(modelAttribute?.KeyPrefix))
prefix = modelAttribute.KeyPrefix;
var resourceAttributeOnClass = containerType.GetCustomAttribute<LocalizedResourceAttribute>();
if(!string.IsNullOrEmpty(resourceAttributeOnClass?.KeyPrefix))
prefix = resourceAttributeOnClass.KeyPrefix;
return prefix.JoinNonEmpty(string.Empty, propertyResourceKeyAttribute.Key);
}
}
// we need to understand where to look for the property
// 1. verify that property is declared on the passed in container type
if(modelAttribute == null || modelAttribute.Inherited)
return containerType.FullName.JoinNonEmpty(separator, propertyName);
// 2. if not - then we scan through discovered and cached properties during initial scanning process and try to find on which type that property is declared
var declaringTypeName = FindPropertyDeclaringTypeName(containerType, propertyName);
return declaringTypeName != null
? declaringTypeName.JoinNonEmpty(separator, propertyName)
: containerType.FullName.JoinNonEmpty(separator, propertyName);
}
示例4: Create
public static TypeInfo Create(Type rootType, Func<Type, IEntityMetaDataProvider> provider)
{
if (null == rootType)
throw new ArgumentNullException(nameof(rootType));
if (null == provider)
throw new ArgumentNullException(nameof(provider));
TypeInfo typeInfo = new TypeInfo();
typeInfo.Id = rootType.FullName; //NosQL Id.
typeInfo.Pageable = rootType.GetCustomAttribute<GridPageableAttribute>();
typeInfo.Sortable = rootType.GetCustomAttribute<GridSortableAttribute>();
typeInfo.Filterable = rootType.GetCustomAttribute<GridFilterableAttribute>();
typeInfo.Editable = rootType.GetCustomAttribute<GridEditableAttribute>();
GridAttribute ga = rootType.GetCustomAttribute<GridAttribute>();
if (null != ga)
{
typeInfo.Groupable = ga.Groupable;
typeInfo.Height = ga.Height;
}
LoadFields(typeInfo, null, rootType, provider);
return typeInfo;
}
示例5: LoadForInside
private void LoadForInside (Type type)
{
var atts2 = type.GetCustomAttribute<SaguaAllowXiakeTypeAttribute>();
if (atts2 != null)
XiakeTypes = atts2.XiakeType;
var att3 = type.GetCustomAttribute<SaguaLoadWhenLoginModuleAttribute>();
if (att3 != null)
IsMustLoged = true;
}
示例6: Register
public static void Register(Type type)
{
var actor = type.GetCustomAttribute<ActorAttribute>();
var worker = type.GetCustomAttribute<WorkerAttribute>();
if (actor != null && worker != null)
throw new InvalidOperationException("A type cannot be configured to be both Actor and Worker: " + type);
factories.Add(type, worker != null
? GetWorkerFactory()
: GetActorFactory(actor));
}
示例7: GetModelName
// Modify this to provide custom model name mapping.
public static string GetModelName(Type type)
{
var modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();
if (modelNameAttribute != null && !string.IsNullOrEmpty(modelNameAttribute.Name))
{
return modelNameAttribute.Name;
}
var modelName = type.Name;
if (type.IsGenericType)
{
// Format the generic type name to something like: GenericOfAgurment1AndArgument2
var genericType = type.GetGenericTypeDefinition();
var genericArguments = type.GetGenericArguments();
var genericTypeName = genericType.Name;
// Trim the generic parameter counts from the name
genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
var argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();
modelName = string.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName,
string.Join("And", argumentTypeNames));
}
return modelName;
}
示例8: GetRootElementName
public static string GetRootElementName(Type objectType, out string rootNamespace)
{
var xmlRootAttribute = objectType.GetCustomAttribute<XmlRootAttribute>(true);
string elementName;
if (xmlRootAttribute != null)
{
elementName = !String.IsNullOrEmpty(xmlRootAttribute.ElementName) ? xmlRootAttribute.ElementName : objectType.Name;
rootNamespace = xmlRootAttribute.Namespace;
}
else
{
elementName = objectType.Name;
rootNamespace = null;
}
var pluralization = PluralizationService.CreateService(CultureInfo.CurrentCulture);
if (!pluralization.IsPlural(elementName))
{
elementName = pluralization.Pluralize(elementName);
}
return elementName;
}
示例9: HasFlagsInternal
private static bool HasFlagsInternal(Type type)
{
Contract.Assert(type != null);
FlagsAttribute attribute = type.GetCustomAttribute<FlagsAttribute>(inherit: false);
return attribute != null;
}
示例10: clsMyType
internal clsMyType(Type t)
{
// create mytype.
this.TypeName = t.Name;
this.FullName = t.FullName;
// set wmi class name to use.
var attribWmiClassName = t.GetCustomAttribute<WmiClassNameAttribute>();
if (attribWmiClassName != null)
this.WmiClassName = attribWmiClassName.WmiClassName;
else
this.WmiClassName = t.Name;
// Compile createobject.
//this.CreateObject = Reflection.CompileCreateObject(t);
this.CreateObject = Reflection.Instance.TryGetCreateObject(t.FullName, t);
var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public); // | BindingFlags.SetProperty
foreach(var p in props)
{
var myprop = new clsMyProperty(p);
WmiProperties.Add(myprop.WmiName, myprop);
}
}
示例11: CustomJsonSerializer
private CustomJsonSerializer(Type type, bool encrypt, JsonMappings mappings, bool shouldUseAttributeDefinedInInterface)
{
_mappings = mappings;
_shouldUseAttributeDefinedInInterface = shouldUseAttributeDefinedInInterface;
_type = type;
if (_mappings.MappingsByType.ContainsKey(type))
{
_type = _mappings.MappingsByType[type];
}
else
{
var mappingAttribute = _type.GetCustomAttribute<JsonMappingAttribute>();
if (mappingAttribute != null)
{
_type = mappingAttribute.Type;
}
}
_encrypt = encrypt || type.GetCustomAttribute<EncryptAttribute>() != null;
var serializableProperties = GetSerializableProperties(_type);
_deserializingPropertiesMap = serializableProperties.ToDictionary(p => p.Name);
if (!_type.IsAbstract)
{
_serializingPropertiesMap[_type] = serializableProperties;
}
_createObjectFactory = new Lazy<Func<IObjectFactory>>(GetCreateObjectFactoryFunc);
}
示例12: GetTableInfo
internal static TableInfo GetTableInfo( Type t )
{
TableInfo table;
if ( _tableNameCache.TryGetValue( t, out table ) ) return table;
table = new TableInfo();
table.TableName = t.Name;
table.SchemaName = "dbo";
// check for an attribute specifying something different
var tableAttribute = t.GetCustomAttribute<TableAttribute>( false );
if ( tableAttribute != null )
{
table.TableName = tableAttribute.Name;
if ( !string.IsNullOrWhiteSpace( tableAttribute.Schema ) ) table.SchemaName = tableAttribute.Schema;
}
// get the property names that can be mapped
foreach ( var pi in t.GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ).Where( m => m.CanRead && m.CanWrite && !m.HasCustomAttribute<NotMappedAttribute>( false ) ) )
table.FieldNames.Add( GetFieldName( pi ) );
// get the key property names
foreach ( var pi in t.GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ).Where( m => m.CanRead && m.CanWrite && m.HasCustomAttribute<System.ComponentModel.DataAnnotations.KeyAttribute>( false ) ) )
table.PrimaryKeyFieldNames.Add( GetFieldName( pi ) );
// try to add the newly aquired info
if ( _tableNameCache.TryAdd( t, table ) ) return table;
return _tableNameCache[ t ];
}
示例13: GetLifecycle
/// <summary>
/// 获取生命周期
/// </summary>
public static Lifecycle GetLifecycle(Type type)
{
if (!type.IsDefined(typeof(LifeCycleAttribute), false))
return Lifecycle.Singleton;
return type.GetCustomAttribute<LifeCycleAttribute>(false).Lifetime;
}
示例14: RegisterVisualizer
public static void RegisterVisualizer(Type type)
{
var attribute = type.GetCustomAttribute<ResponseVisualizerAttribute>();
if (attribute != null)
{
foreach (var contentType in attribute.ContentTypes)
{
List<Type> list;
if (!visualizersByContentType.TryGetValue(contentType, out list))
{
list = new List<Type>();
visualizersByContentType[contentType] = list;
}
list.Add(type);
}
}
var predicateMethod = type.GetMethods().Where(x => x.IsDefined(typeof(ResponseVisualizerPredicateAttribute))).SingleOrDefault();
if (predicateMethod != null)
{
if (!predicateMethod.IsStatic)
throw new Exception("ResponseActionPredicate must be a static method");
if (predicateMethod.ReturnType != typeof(bool))
throw new Exception("Return type of a ResponseActionPredicate must be bool");
if (predicateMethod.GetParameters().Length != 1 || predicateMethod.GetParameters()[0].ParameterType != typeof(ApiResponseModel))
throw new Exception("ResponseActionPredicate must declare one parameter of type ApiResponseModel");
RegisterVisualizer(type, x => (bool)predicateMethod.Invoke(null, new[] { x }));
}
}
示例15: Reflect
/// <summary>
/// Makes grid from attribute
/// </summary>
/// <param name="t">Entity for reflection</param>
/// <param name="mode">Template render mode</param>
/// <returns>Grid class</returns>
public Grid Reflect(Type t, TemplateMode mode)
{
var attribute = (GridPropertiesAttribute)t.GetCustomAttribute(typeof(GridPropertiesAttribute));
if (attribute != null)
{
var grid = new Grid(attribute);
var rows = new List<GridRow>();
foreach (var property in t.GetProperties())
{
var rowAttribute = (RowDisplayAttribute)property.GetCustomAttribute(typeof(RowDisplayAttribute));
if (rowAttribute != null)
{
if (mode == TemplateMode.ExtendedDisplay || !rowAttribute.ExtendedView)
{
if (mode == TemplateMode.Edit && rowAttribute.ColumnEditType == GridColumnTypes.DropDown)
{
rows.Add(new GridRow(t.GetProperty(rowAttribute.DropdownPropertyName), rowAttribute, mode));
}
else
{
rows.Add(new GridRow(property, rowAttribute, mode));
}
}
}
}
grid.Rows = rows.ToList();
return grid;
}
return null;
}