有没有办法在C#中设置从字符串到接口类型的隐式转换 [英] Is there a way to set an implicit conversion from a string to an interface type in C#

查看:64
本文介绍了有没有办法在C#中设置从字符串到接口类型的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我正在使用的具有以下界面的库:

I have a library that I'm using that has the following interface:

public interface IStringType
{
    string GetValue();
    bool IsSet();
    void SetValue(string val);
}



所以,当我去使用它时,我需要做这样的检查:


So, when I go to use this, I need to do checks like so:

public void ReadName(IStringType i)
{
    string Name;

    if(i != null)
    {
        Name = i.GetValue();
    }
    else
    {
        Name = string.Empty;
    }
}



理想情况下,我希望能够做到这一点:


Ideally, I'd like to just be able to do this:

public void ReadName(IStringType i)
{
    string Name = i;
}



我发现了一些关于进行隐式转换的信息,但是当你创建自己的接口/类时,它似乎更适用于使用其他现有的。


I found some information on doing implicit conversions, but it seems like it more geared for when you are creating your own interfaces/classes, not trying to use others existing ones.

推荐答案

麻烦的是你不能在界面中实现任何代码,所以你不能创建一个隐式的强制转换操作符!



没有真正的解决方案:除了声明一个虚拟派生类或派生类的静态实例是空的:

Trouble is that you can't implement any code in an interface, so you can't create a implicit cast operator!

There is no real solution: Except to declare a "dummy" derived class or a static instance of a derived class that is empty:
public interface IStringType
    {
    string GetValue();
    bool IsSet();
    void SetValue(string val);
    }
public class ConcreteStringType : IStringType
    {
    public string GetValue() { return string.Empty; }
    }
public void ReadName(IStringType i)
    {
    string Name = (i ?? new ConcreteStringType()).GetValue();
    }






Or

public interface IStringType
    {
    string GetValue();
    bool IsSet();
    void SetValue(string val);
    }
public class DerivedStringType : IStringType
    {
    }
public static DerivedStringType inst = new DerivedStringType();
public void ReadName(IStringType i)
    {
    string Name = (i ?? inst).GetValue();
    }



讨厌......


Nasty...


这篇关于有没有办法在C#中设置从字符串到接口类型的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆