是否可以实现自定义安全转换(在任意抽象数据结构之间使用 "as")?
Is it possible to implement custom safe cast (using "as" between arbitrary abstract data structures)?
今天,我们有一组 classes,它们在处理数据传输时相互转换为彼此的类型 from/to 客户端。转换范例在目标的构造函数中实现(即每个对象都知道如何根据输入的类型创建自己)。我们有意拒绝让对象知道如何将自己转换为目标类型的想法(即每个对象都有一组 ToTypeXyz() 方法),因为它在我们的案例中出于可维护性目的更有意义.
class ThisType
{
public ThisType() { ... }
public ThisType(ThatType input) { ... }
...
}
class ThatType
{
public ThatType() { ... }
public ThatType(ThisType input) { ... }
...
}
我正在考虑移出所有转换逻辑以集中所有工作。一种选择是引入带有静态方法的实用程序 class(特殊情况是扩展方法以获得更好的编码体验)。
但是,如果转换可以通过安全转换进行,即像下面的示例那样使用 as,那么在我们的例子中会特别好。它还会提高性能并降低异常风险,I think。
ThisType input = new ThisType();
...
ThatType target = input as ThatType;
然而,当我用谷歌搜索“custom safe cast c#”时,我没有得到相关结果,可能淹没在标准案例的噪音中。有可能吗?
是,使用隐式/显式 conversion operator:
class ThatType
{
public ThatType() { ... }
public ThatType(ThisType input) { ... }
...
public static implicit operator ThatType(ThisType t) => new ThatType(t);
}
对于上面的隐式版本,这将起作用:
ThisType input = new ThisType();
ThatType target = input;
尽管不幸的是 as
运算符将不起作用,因为它不遵守用户定义的转换。
The as operator considers only reference, nullable, boxing, and unboxing conversions. You cannot use the as operator to perform a user-defined conversion. To do that, use the cast operator ().
由于您的转换不在任何这些条件下,您几乎只能使用转换运算符。
今天,我们有一组 classes,它们在处理数据传输时相互转换为彼此的类型 from/to 客户端。转换范例在目标的构造函数中实现(即每个对象都知道如何根据输入的类型创建自己)。我们有意拒绝让对象知道如何将自己转换为目标类型的想法(即每个对象都有一组 ToTypeXyz() 方法),因为它在我们的案例中出于可维护性目的更有意义.
class ThisType
{
public ThisType() { ... }
public ThisType(ThatType input) { ... }
...
}
class ThatType
{
public ThatType() { ... }
public ThatType(ThisType input) { ... }
...
}
我正在考虑移出所有转换逻辑以集中所有工作。一种选择是引入带有静态方法的实用程序 class(特殊情况是扩展方法以获得更好的编码体验)。
但是,如果转换可以通过安全转换进行,即像下面的示例那样使用 as,那么在我们的例子中会特别好。它还会提高性能并降低异常风险,I think。
ThisType input = new ThisType();
...
ThatType target = input as ThatType;
然而,当我用谷歌搜索“custom safe cast c#”时,我没有得到相关结果,可能淹没在标准案例的噪音中。有可能吗?
是,使用隐式/显式 conversion operator:
class ThatType
{
public ThatType() { ... }
public ThatType(ThisType input) { ... }
...
public static implicit operator ThatType(ThisType t) => new ThatType(t);
}
对于上面的隐式版本,这将起作用:
ThisType input = new ThisType();
ThatType target = input;
尽管不幸的是 as
运算符将不起作用,因为它不遵守用户定义的转换。
The as operator considers only reference, nullable, boxing, and unboxing conversions. You cannot use the as operator to perform a user-defined conversion. To do that, use the cast operator ().
由于您的转换不在任何这些条件下,您几乎只能使用转换运算符。