如何根据预期的返回值以不同方式处理动态类

时间:2013-01-04 10:46:52

标签: c# .net dynamic dynamicobject

为了根据使用实例的上下文获取不同的行为(在动态类中),我必须覆盖DynamicObject的哪种方法?

这是我想要完成的一个例子:

class DynamicTest : DynamicObject
{
    public DynamicTest(string xyz)
    {
        _xyz = xyz;
    }

    private string _xyz;

    //TODO: what do I need to implement to get required behaviour?
}

class Program
{
    static void Main(string[] args)
    {
        dynamic foo = new DynamicTest("test);

        if (foo)  // treat foo as boolean
        { // jump in here when _xyz of foo has a value
            System.Console.WriteLine(foo); //treat foo as string
        }
        else
        { // jump in here when _xyz of foo is null
            System.Console.WriteLine("No Value In Object");
        }
    }
}

2 个答案:

答案 0 :(得分:2)

我不知道你为什么要这样做,我肯定 NOT 会建议这样做,但你可以在DynamicObject上覆盖TryConvert方法,如:

class DynamicTest : DynamicObject
{
    public DynamicTest(string xyz)
    {
        _xyz = xyz;
    }
    private string _xyz;


    public override bool TryConvert(ConvertBinder binder, out Object result)
    {
        Console.WriteLine ("TryConvert was called");
        Console.WriteLine ("Is explicit: "+binder.Explicit);
        if(binder.Type == typeof(bool))
        {
            result = true;
            return true;
        }
        else if(binder.Type == typeof(string))
        {   
            result = _xyz;
            return true;
        }

        result = null;
        return false;
    }

    public override string ToString()
    {
        return _xyz;
    }
}

现在存在一些问题:ToString需要Console.WriteLine,如果不存在隐式转换,则不会尝试转换(因为WriteLine已重载),因此它会调用{ {1}}。 ToString传递的隐式和显式转换,但如果您在内部使用foo,则会获得bool

<强>示例:

RuntimeBinderException: Cannot implicitly convert type 'DynamicTest' to 'bool'

答案 1 :(得分:0)

我认为implicit operator可以帮助您

示例代码:

class DynamicTest : DynamicObject
{
    public DynamicTest(string xyz)
    {
        _xyz = xyz;
    }

    private string _xyz;

    public static implicit operator bool(DynamicTest rhs)
    {
        return rhs._xyz != null;
    }

    public static implicit operator string(DynamicTest rhs)
    {
        return rhs._xyz;

    }

    //TODO: what to override to get required behaviour
}



class Program
{
    static void Main(string[] args)
    {
        dynamic foo = new DynamicTest("test");


        if (foo)  // treat foo as boolean
        { // jump in here when _xyz of foo has a value
            System.Console.WriteLine((string)foo); //treat foo as string   //Importat: (string)foo to go operatorstring 
        }
        else
        { // jump in here when _xyz of foo is null
            System.Console.WriteLine("No Value In Object");
        }


    }
}