相关疑难解决方法(0)

C#类可以从其接口继承属性吗?

这似乎意味着"不".哪个是不幸的.

[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class,
 AllowMultiple = true, Inherited = true)]
public class CustomDescriptionAttribute : Attribute
{
    public string Description { get; private set; }

    public CustomDescriptionAttribute(string description)
    {
        Description = description;
    }
}

[CustomDescription("IProjectController")]
public interface IProjectController
{
    void Create(string projectName);
}

internal class ProjectController : IProjectController
{
    public void Create(string projectName)
    {
    }
}

[TestFixture]
public class CustomDescriptionAttributeTests
{
    [Test]
    public void ProjectController_ShouldHaveCustomDescriptionAttribute()
    {
        Type type = typeof(ProjectController);
        object[] attributes = type.GetCustomAttributes(
            typeof(CustomDescriptionAttribute),
            true);

        // NUnit.Framework.AssertionException:   Expected: 1   But …
Run Code Online (Sandbox Code Playgroud)

c# attributes

110
推荐指数
4
解决办法
6万
查看次数

接口成员的属性不起作用

在我的应用程序中,有几个模型需要Password属性(例如RegistrationChangePassword模型).该Password物业具有DataType和的属性Required.因此,为了确保可重用性的一致性,我创建了:

interface IPasswordContainer{
    [Required(ErrorMessage = "Please specify your password")]
    [DataType(DataType.Password)]
    string Password { get; set; }
} 
Run Code Online (Sandbox Code Playgroud)

class RegistrationModel : IPasswordContainer {
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,属性不起作用.

然后我尝试将界面更改为类:

public class PasswordContainer {
    [Required(ErrorMessage = "Please specify your password")]
    [DataType(DataType.Password)]
    public virtual string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

public class RegistrationModel : PasswordContainer {
    public override string Password { get; set; } …
Run Code Online (Sandbox Code Playgroud)

c# attributes annotations interface

18
推荐指数
1
解决办法
1万
查看次数

标签 统计

attributes ×2

c# ×2

annotations ×1

interface ×1