C# 如何根据预期的返回值以不同的方式处理动态类
为了根据实例使用的上下文获得不同的行为(在动态类中),我必须重写C# 如何根据预期的返回值以不同的方式处理动态类,c#,.net,dynamic,dynamicobject,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 require
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");
}
}
}
我不知道您为什么要这样做,我肯定不会会建议您这样做,但您可以在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
是控制台所必需的。WriteLine
,如果不存在隐式转换,它不会尝试转换(因为WriteLine
被重载),因此它调用ToString
。隐式和显式转换为bool
pass,但如果在if-中使用foo,则会得到RuntimeBinderException:无法隐式将类型“DynamicTest”转换为“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
我想我能帮你
示例代码:
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");
}
}
}
请问你为什么要这样做?为什么不想访问某个谓词中的字段呢?在python中,有值的字段被视为true,没有值的字段被视为false。我想要一个类似的行为。我想要这个行为,因为在许多动态语言中,有值的对象被认为是真的,没有值的对象被认为是假的。在没有动态关键字的c#中,您需要显式比较。什么是好的,但不是在api我的工作。