C# 使用内部逻辑创建自定义属性
我这里有一个自定义属性,它执行一些逻辑C# 使用内部逻辑创建自定义属性,c#,.net,attributes,C#,.net,Attributes,我这里有一个自定义属性,它执行一些逻辑 [AttributeUsage(AttributeTargets.All)] public class CustomAttribute : Attribute { public CustomAttribute () { bool foo = false; if (foo) Console.WriteLine ("TRUE"); } } 然后我想像这样在我的组件类中使用它 [C
[AttributeUsage(AttributeTargets.All)]
public class CustomAttribute : Attribute
{
public CustomAttribute ()
{
bool foo = false;
if (foo)
Console.WriteLine ("TRUE");
}
}
然后我想像这样在我的组件类中使用它
[Custom]
public class Component
{
public void Test()
{
console.log("test");
}
}
所以我想要的是,每当我创建一个组件类的实例时,它基本上会调用或执行属性中的代码来执行一些逻辑,但问题是,它不会执行自定义属性类中的代码。我知道我做错了,有人知道怎么做吗?当类被实例化时,它不会内在地调用任何绑定到属性的代码,甚至不会实例化它。只有在使用反射调用属性时,属性才会被实例化。如果希望在构造类时处理属性,则必须在组件类的构造函数中调用一个方法,该方法使用反射来分析类上的属性 理想的方法是从具有构造函数逻辑的基类继承:
public class Component : CustomBase
{
public void Test()
{
console.log("test");
}
}
public abstract class CustomBase
{
public CustomBase()
{
bool foo = false;
if (foo)
Console.WriteLine ("TRUE");
}
}
您需要拨打:
object[] attributes = typeof(MyClass).GetCustomAttributes(true);
因为这是触发属性构造函数运行的代码。
您可以在属性类中创建一个调用此行的方法,并在组件中创建一个调用attribute方法的方法。正如Jason和Cristina所说,您需要考虑使用自定义属性编写代码的反射。如果您阅读下面的代码(从第18行到第24行),您可以看到一些注释掉的代码,其中列出了与类型关联的所有CustomAttribute
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomAttributeTest
{
class Program
{
static void Main(string[] args)
{
var customCompo = new Component();
customCompo.Test();
//System.Reflection.MemberInfo info = typeof(Component);
//object[] attributes = info.GetCustomAttributes(true);
//for (int i = 0; i < attributes.Length; i++)
//{
// System.Console.WriteLine(attributes[i]);
//}
Console.ReadLine();
}
}
[CustomAttribute(true)]
public class Component
{
public void Test()
{
System.Console.WriteLine("Component contructed");
var member = typeof(Component);
foreach (object attribute in member.GetCustomAttributes(true))
{
if (attribute is CustomAttribute)
{
//noop
}
}
}
}
[AttributeUsage(AttributeTargets.All)]
public class CustomAttribute : Attribute
{
private bool _value;
//this constructor specifes one unnamed argument to the attribute class
public CustomAttribute(bool value)
{
_value = value;
Console.WriteLine(this.ToString());
}
public override string ToString()
{
string value = "The boolean value stored is : " + _value;
return value;
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.ComponentModel.Design;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
命名空间CustomAttributeTest
{
班级计划
{
静态void Main(字符串[]参数)
{
var customCompo=新组件();
customCompo.Test();
//System.Reflection.MemberInfo=类型(组件);
//object[]attributes=info.GetCustomAttributes(true);
//for(int i=0;i
下面是一个很好的示例,显示了何时运行属性构造函数:。如果您想在每次创建组件的新实例时执行代码,那么为什么不在组件
构造函数中使用该代码呢?