C# 有关用户定义转换的错误
我的Visual Web部件的代码隐藏文件中有以下运算符:C# 有关用户定义转换的错误,c#,sharepoint,web-parts,C#,Sharepoint,Web Parts,我的Visual Web部件的代码隐藏文件中有以下运算符: public static implicit operator TemplateControl (ScholarChip.PaymentProcessor.PaymentProcessor.PaymentProcessor target) { return ((target == null) ? null : target.TemplateControl); } 我收到错误信息: User-define
public static implicit operator TemplateControl
(ScholarChip.PaymentProcessor.PaymentProcessor.PaymentProcessor target)
{
return ((target == null) ? null : target.TemplateControl);
}
我收到错误信息:
User-defined conversion must convert to or from the enclosing type
我不熟悉上述错误。有人能建议我如何纠正它吗?该代码正在Sharepoint 2010可视化Web部件中使用
非常感谢:)问题是您正在定义
PaymentProcessor
和TemplateControl
之间的转换,但是您没有在PaymentProcessor
类或TemplateControl
类中定义该转换。TemplateClass似乎是框架的一部分,因此我怀疑您是否可以在该类中定义转换
用户定义的转换必须是正在转换的两种类型之一的成员(这只是说明错误消息所述内容的另一种方式)。换句话说,如果您控制PaymentProcessor类,请将转换移动到该类中。如果两个类都不控制,那就太倒霉了,需要用普通方法处理转换
例如,这将给出与您看到的相同的编译器错误:
class A {}
class B {}
class C
{
public static implicit operator A(B source) { return new A(); }
}
这将汇编:
class A {}
class B
{
public static implicit operator A(B source) { return new A(); }
}
这也将:
class A
{
public static implicit operator A(B source) { return new A(); }
}
class B {}
谢谢你的解释。TemplateControl似乎是System.Web.UI的一部分。这对如何处理上述错误有什么影响吗?@SidC抱歉,出于某种原因,我错过了前面的评论。TemplateControl是一个框架类,这意味着您必须在
PaymentProcessor
类中定义从PaymentProcessor
到TemplateControl
的转换,因为它必须在那里或TemplateControl
类中,但您不能修改TemplateControl
类。如果您也不能修改PaymentProcessor
,那么可以编写一个扩展方法来处理空检查。