提问人:Nick 提问时间:12/12/2019 最后编辑:Dmitry BychenkoNick 更新时间:9/8/2022 访问量:2839
C# 如何使用两个参数设置属性
C# How to set Property with two arguments
问:
我需要设置一个带有两个参数的属性,例如,在日志文件中附加文本。 例:
public string LogText(string text, bool Overwrite)
{
get
{
return ProgramLogText;
}
set
{
ProgramLogText = value;
}
}
我该怎么做? (在上面的例子中,我需要传递我想写在文件中的文本,1 覆盖(0 作为附加文本的默认值),否则附加到文本文件,但当我得到时,我只需要文本。
答:
4赞
Lucca Ferri
12/12/2019
#1
你不能。
但是,您有几种可能的替代方法:创建一个方法,或者改用元组,或者创建一个类/结构并作为参数传递(其他人已经回答了)。
以下是一些也可以使用的替代方法。
替代方法 1
创建一个元组,但随后你必须返回一个元组字符串 bool。
public Tuple<string, bool> LogText { get; set; }
我不会做这个方法,因为那样你的 getter 也会返回两个值。
替代方法 2
请改为创建 getter 和 setter 方法。
public string GetLogText() => ProgramLogText;
public void SetLogText(string text, bool overwrite) => ProgramLogText = text; // and implement in this method your use of overwrite.
6赞
Dmitry Bychenko
12/12/2019
#2
你可以提取类 - 用 and 属性实现你自己的 () 并添加一些语法糖:class
struct
Text
Overwrite
public struct MyLogText {
public MyLogText(string text, bool overwrite) {
//TODO: you may want to validate the text
Text = text;
Overwrite = overwrite;
}
public string Text {get;}
public bool Overwrite {get;}
// Let's add some syntax sugar: tuples
public MyLogText((string, bool) tuple)
: this(tuple.Item1, tuple.Item2) { }
public void Deconstruct(out string text, out bool overwrite) {
text = Text;
overwrite = Overwrite;
}
public static implicit operator MyLogText((string, bool) tuple) => new MyLogText(tuple);
//TODO: You may want to add ToString(), Equals, GetHashcode etc. methods
}
现在你可以放一个简单的语法
public class MyClass {
...
public MyLogText LogText {
get;
set;
}
...
}
并且易于分配(就好像我们有一个具有 2 个值的属性):
MyClass demo = new MyClass();
// Set two values in one go
demo.LogText = ("some text", true);
// Get two values in one go
(string text, bool overWrite) = demo.LogText;
评论
0赞
Nick
12/12/2019
只是一件事,因为我是新手:我有另一个类,所以我尝试实现上述内容。我在一个新的公共类中创建了 autoproperty,其中没有其他内容,但是当我尝试 LogText = (“something”, true) 时;我得到了“名称 LogText 在当前上下文中不存在” - 有什么建议吗?
0赞
Dmitry Bychenko
12/12/2019
@Nick:似乎你在类外调用了属性;您可能必须创建实例等。我更改了我的用法示例。MyClass demo = new MyClass();
0赞
Nick
12/12/2019
是的,你当然是对的。非常感谢,工作完美。
0赞
Boppity Bop
9/7/2022
没有人会想到这样的解决方案。向@DmitryBychenko致敬。但是,任何人都不应该尝试在上述解决方案实际上是巨大的混淆中轻易地编写文件。一件事是以“花哨的方式”设置字段,另一件事是访问外部非托管资源。
评论