C#错误:接口成员无法定义

bol*_*ire 0 c# interface member

我是C#的新手,我不明白为什么我不能这样做.有人可以提供一个可以达到相同结果的链接或示例.

public interface IEffectEditorControl
{
    object[] EffectParameterValues
    {
        get;
        set { isDirty = true; }
    }
    bool isDirty { get; set; }
    IEffect TargetEffect { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Gro*_*roo 12

你的编译器是对的,interface成员确实无法定义.

一个interface限定了合同的一类,即,必须由类实现的属性和方法的列表.它不能包含实际代码,isDirty = true;例如示例中的语句.

换句话说,您应该将其更改为:

// this only lists all the members which a class must implement,
// if it wants to implement the interface and pass compilation 
public interface IEffectEditorControl
{
    object[] EffectParameterValues { get; set; }  // <-- removed the statement
    bool IsDirty { get; set; }
    IEffect TargetEffect { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后通过提供必要的代码来class 实现接口:

// whichever code accepts the interface IEffectEditorControl,
// can now accept this concrete implementation (and you can have 
// multiple classes implementing the same interface)
public class EffectEditorControl : IEffectEditorControl
{
    private object[] _effectParameterValues; 
    public object[] EffectParameterValues
    {
        get
        { 
            return _effectParameterValues;
        }
        set
        { 
            _effectParameterValues = value;
            IsDirty = true;
        }
    }

    public bool IsDirty { get; set; }
    public IEffect TargetEffect { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

另外,请注意它们之间的区别EffectParameterValues,它是带有支持字段(_effectParameterValues)的完整属性,和IsDirty/ TargetEffect,它们是具有私有匿名支持字段的自动实现属性.将EffectParameterValues值设置为一个值将执行整个setter块,同时修改后备字段和IsDirty属性.

当您需要获取/设置访问器时,不仅要分配单个值(如IsDirty本示例中的设置),您需要添加实际的后备字段并自行完成整个逻辑.否则,您可以使用更简单的变体.

扩展方法有时可以执行相同的任务.

或者,如果您确实具有接口的通用功能,则可以使用扩展方法.请注意,这仍然不会向接口添加实际代码,但实质上会创建静态方法,可以方便地在实现该接口的每个类上调用它们.

在这种情况下,您可以让课程"哑"并使其自动实现所有内容:

// setting the EffectParameterValues directly won't
// set the IsDirty flag in this case
public class EffectEditorControl : IEffectEditorControl
{
    public object[] EffectParameterValues { get; set; }
    public bool IsDirty { get; set; }
    public IEffect TargetEffect { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

...然后在界面中添加扩展方法:

public static class IEffectEditorControlExtension
{
    public static void SetParametersAndMarkAsDirty
        (this IEffectEditorControl obj, object[] value)
    {
        obj.EffectParameterValues = value;
        obj.IsDirty = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

...然后记得稍后通过该方法分配参数:

// this will call the static method above
editor.SetParametersAndMarkAsDirty(parameters);
Run Code Online (Sandbox Code Playgroud)

这很可能不是扩展方法的最佳用例(没有什么可以阻止你EffectParameterValues直接设置和搞乱整个事情),但我已经为了完整性而添加了它.