0

我必须重写哪种方法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");
        }
    }
}
4

2 回答 2

2

我不知道你为什么要这样做,我绝对不会推荐这样做,但你可以覆盖 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,所以它调用ToString. 要传递的隐式和显式转换bool,但如果你在 if - 中使用 foo,你会得到RuntimeBinderException: Cannot implicitly convert type 'DynamicTest' to 'bool'.

例子:

dynamic foo = new DynamicTest("test:");
bool boolFoo = foo; //passes, TryConvert is called with `binder.Explicit` == false
bool boolFoo1 = (bool)foo; //passes, TryConvert is called with `binder.Explicit` == true
if(foo) //throws RuntimeBinderException
于 2013-01-04T11:01:54.107 回答
0

我认为隐式运算符可以帮助你

示例代码:

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");
        }


    }
}
于 2013-01-04T11:56:03.983 回答