【问题标题】:C# Expandable PropertyC# 可扩展属性
【发布时间】:2017-02-03 19:35:25
【问题描述】:
    public class ThemeProperty
    {
        public Color FColor { get; set; } = Color.White;
        public Color BColor { get; set; } = Color.Black;
    }

    [TypeConverter(typeof(ExpandableObjectConverter))]
    public ThemeProperty Theme { get; set; } = new ThemeProperty();

    // Use. 
    public void Test()
    {
        Theme.BColor = Color.Gray;
        Theme.FColor = Color.Black;
        Theme = true; /*I wanted to make the feature active or passive, but
        I could not figure out how to define a property class for this line.*/
    }

您好,我创建了一个名为 Theme 的可扩展属性。虽然我有两个功能,但如果我是主动或被动的,我想使用它们,如果我是主动的,我想使用它们。我可以在其中创建和控制一个功能,但它不灵活。我想像上面那样定义这个特性,但我不知道该怎么做。非常感谢您的帮助。

我想在红线上添加真假值。激活或停用功能。

【问题讨论】:

    标签: c# syntax properties typeconverter


    【解决方案1】:

    你可以试试这样的:

    public class ThemeProperty
    {
        public Color FColor { get; set; }
        public Color BColor { get; set; }
        public bool ActivePassive { get; set; }
    
        public void ThemeProperty(bool state)
        {
            ActivePassive = state;
            FColor = Color.White;
            BColor = Color.Black;
        }
    }
    

    并使用构造函数通过真/假使主动被动。希望这会有所帮助。

    【讨论】:

    • 我试图用这种方式解释我还不够灵活。谢谢你的回复,我会整理问题的。
    【解决方案2】:

    在“ThemeProperty”类中再定义一个属性。

    public class ThemeProperty
    {        
        public Color FColor { get; set; } = Color.White;
        public Color BColor { get; set; } = Color.Black;
        public bool Active { get; set; } = true;
    }
    
    // Use.
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public ThemeProperty Theme { get; set; } = new ThemeProperty();
    
    
    public void Test()
    {
         Theme.BColor = Color.Gray;
         Theme.FColor = Color.Black;
         Theme.Active = true;
    }
    

    或者,如果需要“活动”,您可能希望将活动的布尔值传递给类的构造函数。此外,作为观察,将类称为“属性”可能不是一个好习惯。任何可以实例化的类都可以用作属性的类型。以下是初始版本的替代方案。

    public class Theme
    {        
        public Theme(bool active)
        {
            Active = active;
        }
    
        public Color FColor { get; set; } = Color.White;
        public Color BColor { get; set; } = Color.Black;
        public bool Active { get; set; }
    }
    
    // Use. 
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public Theme theme { get; set; }
    
    
    public void Test()
    {
        theme = new Theme(true) { BColor = Color.Gray, FColor = Color.Black };
    }
    

    【讨论】:

    • 我试图用这种方式解释我还不够灵活。谢谢你的回复,我会整理问题的。
    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2020-03-28
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多