gpt4 book ai didi

C# 只读与获取

转载 作者:IT王子 更新时间:2023-10-29 04:53:11 26 4
gpt4 key购买 nike

readonly 修饰符和 get-only 属性之间有什么区别吗?

例子:

public class GetOnly
{
public string MyProp { get; }
}

public class ReadOnly
{
public readonly string MyProp;
}

奖励:有没有一种方法可以创建一个同时适用于两者的界面? (与泛型一起使用)

public interface ISomething
{
public string MyProp { get; }
}

public class GetOnly : ISomething
{
public string MyProp { get; }
}

public class ReadOnly : ISomething // Cannot implement
{
public readonly string MyProp;
}

非常感谢!

最佳答案

您从根本上误解了这两个定义的含义。只有公开 getter 才能说明什么一个值是否是只读的。

虽然在这个简单的例子中:

public class GetOnly
{
public string MyProp { get; }
}

我们可以说 MyProp永远改变它的值,我们不能总是说一个 getter-only 属性不会改变它的值。例如,我们无法看到 GetOnly 的实现,并且只知道公共(public)定义 - 例如,如果您正在使用闭源第三方库。

一个更清晰的例子是这样的:

public interface ISomething
{
string MyProp { get; }
}

这个接口(interface)并没有说MyProp是只读的。它说不能改变这个属性。它没有说明属性的行为。更糟糕的是,它只是说当显式转换为 ISomething 时您不能更改属性。

像这样实现接口(interface)是完全可能的(即使接口(interface)只公开了 getter):

public class GetOnly : ISomething
{
public string MyProp { get; set; }
}

readonly 是一个修饰符,它显式强制值永远不会改变,除了在声明或构造函数中(除非像 reflection 这样的变通方法)。

但是,readonly 不能作用于属性,因为属性只是获取/设置方法 的语法糖。此外,接口(interface)仅定义方法,因此您不能定义字段(并且扩展为只读字段)。

所以回答你的问题:是的,它们是天壤之别,只是表面上相似。

关于C# 只读与获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37496738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com