Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将类型用作属性的自定义属性_C#_Custom Attributes - Fatal编程技术网

C# 将类型用作属性的自定义属性

C# 将类型用作属性的自定义属性,c#,custom-attributes,C#,Custom Attributes,我有以下自定义属性,我希望将类型名作为属性。但是,我不希望在使用属性时必须使用类型的字符串表示。例如: public class HelpMeAttribute : Attribute { public string TypeName { get; set; } } 使用它,我想 [HelpMe(TypeName = typeof(MyClass2).FullName] public class MyClass1 { } public class MyClass2 { } 我得到错

我有以下自定义属性,我希望将类型名作为属性。但是,我不希望在使用属性时必须使用类型的字符串表示。例如:

public class HelpMeAttribute : Attribute
{
    public string TypeName { get; set; }
}
使用它,我想

[HelpMe(TypeName = typeof(MyClass2).FullName]
public class MyClass1
{
}

public class MyClass2
{
}
我得到错误:“属性必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式。”

我宁愿不这样做:

[HelpMe(TypeName = "MyClass2"]
因为将类型放在字符串中似乎很糟糕。最好让编译器检查我放在属性中的类型是否存在


有人能告诉我如何解决这个问题吗?

属性初始值设定项只能使用编译时常量或
System.Type
properties

那么为什么不直接使用
类型

public class HelpMeAttribute : Attribute
{
    public Type Type { get; set; }
    ...

    public HelpMeAttribute()
    {
    }
}

...
[HelpMe(Type = typeof(MyClass2))]
public class MyClass1
{
}

属性初始值设定项只能使用编译时常量或
System.Type
properties

那么为什么不直接使用
类型

public class HelpMeAttribute : Attribute
{
    public Type Type { get; set; }
    ...

    public HelpMeAttribute()
    {
    }
}

...
[HelpMe(Type = typeof(MyClass2))]
public class MyClass1
{
}

我认为这不会像现在这样编译。我认为您需要定义一个构造函数,它接受并分配类型。但除此之外,这是正确的,我也会这样做+1具有公共setter的属性的任何属性都可以这样设置。虽然是的,你可以用任何一种方法。啊,我不知道。我确实测试过你的,但我有一个打字错误。我喝了太多酒,认为编译器错误是因为语法不正确。:)我认为这不会像现在这样编译。我认为您需要定义一个构造函数,它接受并分配类型。但除此之外,这是正确的,我也会这样做+1具有公共setter的属性的任何属性都可以这样设置。虽然是的,你可以用任何一种方法。啊,我不知道。我确实测试过你的,但我有一个打字错误。我喝了太多酒,认为编译器错误是因为语法不正确。:)