使用隐式类型转换调用函数

Call Function with Implicit Type Conversion

我有一个class这样的。

public class ForeignKey {
    public string Id {get;}
    public TableA TableA {get;}
    public TableB TableB {get;}
    public static implicit operator string(ForeignKey obj){ return obj.Id; }
    public override string ToString() { return Id; }
    /* various operator overloads */
}

我想对其进行自动类型转换,这样我就可以像字符串一样使用它。到目前为止我所做的让我可以在很多地方使用它而无需显式转换。但是,我想不出不进行显式转换就调用字符串函数的方法。

例如,我想让它工作。

if (Key.EndsWith(someValue))

目前我必须这样做

if (((string)Key).EndsWith(someValue))
// or
if (Key.Id.EndsWith(someValue))

有没有办法让它按照我想要的方式工作?

谢谢

您可以create a extension method将此Key作为参数。

namespace ExtensionMethods
{
  public static class Utilities
  {
    public static bool ValueEndsWith(this Key key, ref string valueToCheck)
    {
      return key.Id.EndsWith(valueToCheck);
    } 
  }
}

你可以这样称呼它 Key.ValueEndsWith(ref valueString);

这无法完成,因为成员查找运算符 . 不考虑除 ForeignKey 之外的其他类型的成员。

第 7.4 节解释了该过程。

A member lookup of a name N with K type parameters in a type T is processed as follows:

  • First, a set of accessible members named N is determined
  • Next, if K is zero, all nested types whose declarations include type parameters are removed. If K is not zero, all members with a different number of type parameters are removed.
  • Next, if the member is invoked, all non-invocable members are removed from the set.
  • Next, members that are hidden by other members are removed from the set.
  • Next, interface members that are hidden by class members are removed from the set. This step only has an effect if T is a type parameter and T has both an effective base class other than object and a non-empty effective interface set.
  • Finally, having removed hidden members, the result of the lookup is determined:
    • If the set consists of a single member that is not a method, then this member is the result of the lookup.
    • Otherwise, if the set contains only methods, then this group of methods is the result of the lookup.
    • Otherwise, the lookup is ambiguous, and a binding-time error occurs.

由于 C# 在成员解析过程中不考虑转换运算符,您唯一的选择是直接或通过扩展将方法添加到您的 class。