在C#中是否可以使用带有访问器的参数

问题描述 投票:0回答:2

我真的很喜欢c#中访问器的语法,但是我需要在setter中使用一些额外的值来获取一些属性。

有什么办法可以执行与此类似的操作,或者使用这种语法是不可能的吗?

public class Accesssor{
    public List<CustomObject> AccessorStuff { 
        get {
                return AccessorStuff;
            } 
        set (ExtraParameters????) => {
                AccessorStuff.add(new CustomObject(value,ExtraParameters))
            }
        }
}

((我也很难找到这个名字,因为我不知道它的名字是否正确,所以如果我也能获得那条信息,我将不胜感激)]

谢谢你。

c# .net accessor
2个回答
4
投票

不,这是不可能的-如果我使用您的财产,这不是我期望的。当我使用set时,我希望更改List,而不是添加值。这通常是通过类方法实现的:

public void AddObject(CustomObjectType obj, ExtraParameters extraParameters) => 
    AccessorStuff.Add(new CustomObject(obj,ExtraParameters));

2
投票

您可以在C#中使用所谓的indexer

public List<CustomObject> this[int index]
{
    get { /* return the specified index here */ }
    set { /* set the specified index to value here */ }
}

您可以通过以下方式访问它

obj[5] = someValue;
var result = obj[0];

与方法完全一样,索引器中可以具有任意数量的任何类型的参数(但至少有一个)。您还可以使索引器超载,即具有不同版本的参数,不同数量的参数或不同的参数类型。例如:

public List<CustomObject> this[string name]
{
    ...
}

public List<CustomObject> this[string name, bool caseSensitive]
{
    ...
}

但是无论如何,索引既适用于设置方法,也适用于获取方法。除具有属性外,无法命名索引器。如果您需要带有参数的服务器“属性”,请使用简单的旧方法。

public void SetProperty(Extra stuff...)
{
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.