我试图为对象实现一些隐式转换。目前,我这样做:在C#中隐式转换而不创建新对象
public class PathSelector
{
private string _path = null;
public string Path
{
get { return _path; }
set
{
if (value != _path)
{
_path = value;
OnPropertyChanged("Path");
}
}
}
static public implicit operator string(PathSelector pathSelector)
{
return pathSelector.Path;
}
static public implicit operator PathSelector(string path)
{
return new PathSelector() { Path = path };
}
}
正如你可以在施法看到String
到PathSelector
我生成一个新的PathSelector
对象。
我用这样的:
public PathSelector PluginPathSelector { get; set; } = new PathSelector();
public string PluginPath
{
get
{
return PluginPathSelector;
}
set
{
PluginPathSelector = value;
}
}
我不喜欢这个解决方案是,我总是创建一个新的对象时,我给你一个字符串转换为PathSelector
对象。这也意味着,在PathSelector
属性中需要set
部分。我想将string
分配给已创建的对象。有没有办法来实现这个?
那么有到不变性(!每次又名创建一个新的对象)的许多好处。由于该方法的静态特性,没有实例抢 - 点是,你可以在任何使用方法点。你应该在你的对象上创建一个方法来合并它们。 –
如何设置PluginPath,设置PluginPathSelector.Path属性(与获取它相同),我没有理由在此处进行隐式转换。实际上我只是看到代码的问题,因为PathSelector是一个实现INotifyPropertyChanged的类(并且实际上它检查了Path在setter中的等价性) – Icepickle
@Ippickle这就是我所做的。但我想实现隐式强制转换,以便在绑定场景中更方便地使用对象 –