属性设置器类型设置为属性的其他值

本文关键字:属性 设置 其他 类型 | 更新日期: 2023-09-27 18:12:01

属性的get访问器返回的类型可能与set访问器使用的类型不同吗?

private string[] artists;
public string[] Artists
{
    get { return artists[0]; } //heree getter return string than string[]
    set { artists = value; OnPropertyChanged("Artist"); }
}

属性设置器类型设置为属性的其他值

不行,这行不通。

您可以添加另一个属性,并将其包含在ONPC中:

public string Artist
{
    get { return artists[0]; }
}
public string[] Artists
{
    // get { return artists; }   // get string[] is optional
    set { artists = value; OnPropertyChanged("Artist"); OnPropertyChanged("Artists");}
}

提供一个带有上下文的预期用途示例,您可能会得到更好的答案。

这是不可能的。您必须创建另一个属性来返回另一个类型。

为什么这是可能的?如果声明了返回类型,则必须返回。

不,不可能。很明显,您的代码是非法的,因为您的get访问器没有履行返回string[]

的义务。
// you define the Artists property as a string[],
// therefore the get accessor must return a string[]
public string[] Artists
{
    // you are returning only a string
    get { return artists[0]; }