简体   繁体   English

我们可以将参数传递给C#属性吗?

[英]Can we pass parameter to C# property?

We have properties for a class which has getter - returns the value 我们有一个具有getter的类的属性-返回值

Ex: 例如:

Public Employee Department
{
get { return GetTheValue("Mid Level") ;} 
}

GetTheValue is our framework method which takes parameter value and returns string. GetTheValue是我们的框架方法,它接受参数值并返回字符串。 The Parameter vlaue is hard coded now which we want to make that dynamic... We want to pass that Parameter Value directly to Property. 现在,参数vlaue已进行了硬编码,我们希望使之动态。我们希望将该参数值直接传递给Property。 Can we pass parameter to property ? 我们可以将参数传递给属性吗? Don't want to make that as method, looking to pass parameter to property only.. how can I achieve this ? 不想将其作为方法,只希望将参数传递给属性..我怎么能做到这一点?

You could use an indexer which resembles a property... 可以使用类似于属性的索引器 ...

public Employee this[string department]
{
    get
    {
        return GetTheValue(department);
    }
}
...

var instance = new Whatever();
var employee = instance["Mid Level"]

but that is abuse . 但这是虐待 I would just use a method instead... 我会改用一种方法...

public Employee GetDepartment(string department)
{
    return GetTheValue(department);
}

What you're doing perfectly describes the purpose of a method. 您正在做的事情完美地描述了方法的目的。 You are looking to do this: 您正在寻找这样做:

public Employee GetDepartment(string value)
{
    return GetTheValue(value);
}

Because what you're asking is to add a parameter to a property, and a property simply is syntactic sugar for two methods, get_xxx and set_xxx where optimizations can be made regarding the calling convention. 因为您要的是在属性中添加参数,而属性只是两个方法的语法糖,即get_xxxset_xxx ,可以在其中对调用约定进行优化。 As such, properties were designed to not be ideal for what you are doing. 因此,属性设计对于您正在执行的操作并不理想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM