【发布时间】:2017-01-24 04:53:06
【问题描述】:
我需要为将根据给定名称创建文件的函数创建属性在调用函数之前,或者即使没有调用函数。
例如,如果我有 [some("C:\\hello.txt")] 属性的函数:
[some("C:\\hello.txt")]
private void foo()
{
// do something
}
当我运行应用程序时,它会在在调用函数之前创建这个文件(“C:\hello.txt”),或者即使没有调用函数强>..
我尝试了两种技术:
1. 在构造函数中创建文件
2. 使用反射创建文件。
但没有一个对我有用。
第一次尝试(使用构造函数):
每次有新属性时,我都尝试在构造函数中创建文件。
在这种方法中,我尝试在进入 Main 函数之前创建文件。
在解析函数时,它会找到属性并创建文件。
预期:
应创建两个文件:
1. C:\hello.txt
2. C:\bye.txt
实际上 => 什么都没有发生。
[some("C:\\hello.txt")]
private void foo()
{
// do something
}
[some("C:\\bye.txt")]
private void foo()
{
// do something
}
public class someAttribute : Attribute
{
public someAttribute(string fileToCreate)
{
// File.Create(fileToCreate);
Console.WriteLine("Create file " + fileToCreate);
}
}
static void Main(string[] args)
{
// something
}
第二次尝试(带反射):
预期:
应创建一个文件:
1. C:\hello.txt
实际上 => “类型”变量是空的,并且没有创建任何内容。
[some(fileToCreate = "C:\\hello.txt")]
private void foo()
{
// do something
}
public class someAttribute : Attribute
{
public string fileToCreate {get; set;}
}
static void Main(string[] args)
{
var types = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetCustomAttributes<someAttribute>().Count() > 0
select t;
foreach(var t in types) // types is null
{
string n = t.Name;
foreach(var p in t.GetProperties())
{
// File.Create(fileToCreate)
Console.WriteLine(p.fileToCreate);
}
}
}
【问题讨论】:
-
你有属性函数可能属于的类列表吗?如果是这样,那么这个问题可能会有用:stackoverflow.com/questions/2831809/…。要获取附加到方法的属性,您需要对该方法所属的类使用反射。
-
关于您的第一次尝试(将创建文件代码放在属性的构造函数中),这里回答了它不起作用的原因:stackoverflow.com/questions/1168535/…。
标签: c# reflection attributes