相关疑难解决方法(0)

动态操作员解析

我有一个泛型方法,通过将一个操作数强制转换来调用运算符dynamic.有两种不同的电话:

//array is T[][]
//T is MyClass
array[row][column] != default(T) as dynamic
Run Code Online (Sandbox Code Playgroud)

这是工作和调用static bool operator !=(MyClass a, MyClass b)(即使双方都是null).

让我感到惊讶的是以下行的行为:

//array, a and b are T[][]
//T is MyClass
array[row][column] += a[line][i] * (b[i][column] as dynamic);
Run Code Online (Sandbox Code Playgroud)

这个电话
public static MyClass operator *(MyClass a, object b)
public static MyClass operator +(MyClass a, object b)

而不是
public static MyClass operator *(MyClass a, MyClass b)
public static MyClass operator +(MyClass a, MyClass b).

删除 …

c# dynamic .net-4.5

6
推荐指数
1
解决办法
1624
查看次数

在C#中创建动态扩展方法?

是否可以解决此错误:

public static class LayoutExtensions
{
    /// <summary>
    /// Verifies if an object is DynamicNull or just has a null value.
    /// </summary>
    public static bool IsDynamicNull(this dynamic obj)
    {
        return (obj == null || obj is DynamicNull);
    }
Run Code Online (Sandbox Code Playgroud)

编译时间

Error: The first parameter of an extension method 
       cannot be of type 'dynamic'  
Run Code Online (Sandbox Code Playgroud)

c# .net-4.0

6
推荐指数
1
解决办法
3306
查看次数

奇数行为随var,dynamic和linq组合而变化

我(懒惰地)var在下面的代码的原始版本中使用并在代码的完全不同的部分中获得了奇怪的运行时异常.将"var"更改为"int"修复了运行时异常,但我不明白为什么.我把代码煮成了这个例子;

public class Program
{
    private static List<string> Test(string i) { return new List<string> {i}; }
    private static dynamic GetD() { return 1; }

    public static void Main()
    {
        int value1 = GetD();   // <-- int
        var result1 = Test("Value " + value1);
        // No problem, prints "Value 1", First() on List<string> works ok.
        Console.WriteLine(result1.First());

        var value2 = GetD();   // <-- var
        var result2 = Test("Value " + value2);
        // The below line gives RuntimeBinderException 
        // 'System.Collections.Generic.List<string>' does …
Run Code Online (Sandbox Code Playgroud)

c# linq var dynamic

5
推荐指数
1
解决办法
742
查看次数

C#动态可能存在错误吗?

我遇到过在C#中使用动态变量的问题.这是在编写NancyFx路由模块时出现的,但我已将问题归结为下面的示例.虽然我在原始代码中收到了一个不同的例外,但示例代码仍然会抛出一个我认为是错误的异常.有没有人看到这里发生了什么,或有其他人遇到类似的问题?

请注意,以下帖子可能是相关的: StackOverflowException通过动态访问泛型类型的成员时:.NET/C#framework bug? System.Dynamic错误?

代码:

class Program
{
    static void Main(string[] args)
    {
        var dictionary = new Dictionary<string, object>();
        dictionary.Add("number", 12);
        var result = MethodUsesExplicitDeclaration(dictionary);
        var result2 = MethodUsesImplicitDeclaration(dictionary);
    }

    static dynamic MethodUsesExplicitDeclaration(dynamic reallyDictionary)
    {
        // this works, ostensibly because the local variable is explicitly declared
        IDictionary<string, object> dictionary = CastDictionary(reallyDictionary);
        return dictionary.Get<int>("number");
    }

    static dynamic MethodUsesImplicitDeclaration(dynamic reallyDictionary)
    {
        // this throws an exception, and the only difference is 
        // that the variable declaration is implicit
        var dictionary = …
Run Code Online (Sandbox Code Playgroud)

c# dynamic

5
推荐指数
1
解决办法
2283
查看次数

当我使用'dynamic'来使用AsQueryable方法时,我的代码之间有什么区别?

起初,我不使用dynamic,我只是使用这样的代码,它运作良好.

  List<Student> result2 = StudentRepository.GetStudent(sex,age).ToList();
  IQueryable rows2 = result2.AsQueryable();
Run Code Online (Sandbox Code Playgroud)

但是当我改变它时dynamic,它是错误的.

 dynamic result = GetPeopleData(sex,age);
 IQueryable rows = result.AsQueryable();
Run Code Online (Sandbox Code Playgroud)

我添加了这样的方法,我构建了它显示List没有AsQueryable方法的项目.如何更改它?

 private dynamic GetPeopleData(int sex, int age)
    {
        if(sex>30)
            return StudentRepository.GetStudent(sex,age).ToList();
        else
            return TeacherRepository.GetTeacher(sex, age).ToList();
    }
Run Code Online (Sandbox Code Playgroud)

c# c#-4.0 dynamictype

5
推荐指数
1
解决办法
132
查看次数

为什么在调用IEnumerable.Contains()时需要强制转换动态对象?

我试图IEnumerable.Contains()用一个dynamic参数调用,但我收到了错误

'IEnumerable'不包含'Contains'的定义和最佳扩展方法重载'Queryable.Contains(IQueryable,TSource)'有一些无效的参数

我注意到我可以将参数强制转换为正确的类型,或者使用底层集合类型来解决问题.但我不知道为什么我不能直接传递参数.

dynamic d = "test";
var s = new HashSet<string>();
IEnumerable<string> ie = s;

s.Contains(d);           // Works
ie.Contains(d);          // Does not work
ie.Contains((string)d);  // Works
Run Code Online (Sandbox Code Playgroud)

c# ienumerable contains dynamic

5
推荐指数
1
解决办法
263
查看次数

为什么dynamic.ToString()在字符串而不是字符串之间返回一些东西?

我使用从a派生的类型DynamicObject作为某些字符串的构建器.最后我打电话ToString来获得最终结果.

在这一点上,我认为它会给我一个正常的字符串,但这个字符串有点奇怪.当我在其上使用字符串函数时,它的行为就像一个,但它的行为就像我实际上不知道什么,既不是字符串也不是动态.


这就是我ToString在构建器上实现的方式

public class Example : DynamicObject
{
    public override bool TryConvert(ConvertBinder binder, out object result)
    {
        if (binder.ReturnType == typeof(string))
        {
            result = ToString();
            return true;
        }
        result = null;
        return false;
    }   

    public override string ToString()
    {
        return base.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我像这样运行它

dynamic example = new Example();
Console.WriteLine(example.ToString().ToUpper());
Run Code Online (Sandbox Code Playgroud)

结果是正确的:( USERQUERY+EXAMPLE在LINQPad中执行时)

但是,如果我像这样打电话给第二行

Console.WriteLine(example.ToString().Extension());
Run Code Online (Sandbox Code Playgroud)

哪里

static class Extensions
{
    public static string Extension(this string str)
    {
        return str.ToUpper();
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序崩溃了一个RuntimeBinderException …

c# dynamic tostring

5
推荐指数
1
解决办法
2565
查看次数

扩展功能不适用于动态对象

我有一个以ParseLong字符串命名的扩展函数.

public static long ParseLong(this string x, long Default = 0) 
{ 
if (!string.IsNullOrEmpty(x)) 
     long.TryParse(x, out Default);
 return Default; 
}
Run Code Online (Sandbox Code Playgroud)

工作正常:

long x = "9".ParseLong();
Run Code Online (Sandbox Code Playgroud)

但对于动态对象,例如:

dynamic x = GetValues();
x.StartValue.ToString().ParseLong();
Run Code Online (Sandbox Code Playgroud)

生成错误:

'string'不包含'ParseLong'的定义

c# extension-methods

4
推荐指数
1
解决办法
80
查看次数

为什么在尝试使用动态参数调用扩展方法时出现错误CS1973

请考虑以下代码:

internal static class Program
{
    public static string ExtensionMethod(this string format, dynamic args)
    {
        return format + args.ToString();
    }

    private static void Main()
    {
        string test = "hello ";
        dynamic d = new { World = "world" };

        // Error CS1973  'string' has no applicable method named 'ExtensionMethod'
        //                but appears to have an extension method by that name. 
        //               Extension methods cannot be dynamically dispatched. 
        //               Consider casting the dynamic arguments or calling
        //               the extension method without …
Run Code Online (Sandbox Code Playgroud)

c# extension-methods dynamic dispatch

3
推荐指数
1
解决办法
473
查看次数

C#concat/merge动态类型变量

在for循环中,我从db作为动态类型接收结果

dynamic {system.collections.generic.List<object>}
Run Code Online (Sandbox Code Playgroud)

我需要将这些结果收集到一个变量中.

我尝试定义一个变量

 dynamic results = new List<object>();
Run Code Online (Sandbox Code Playgroud)

然后

 var queryResults = _dbManager.Query(query);
 results = results.Concat(queryResults);
Run Code Online (Sandbox Code Playgroud)

但我有这个例外:

 System.Collections.Generic.List<object> does non contain a definition for 'Concat'
Run Code Online (Sandbox Code Playgroud)

我找不到解决方案.你怎么能这样做?谢谢!

c# concat dynamic

2
推荐指数
1
解决办法
1040
查看次数

可以订购动态类型吗?

说我有以下代码:

dynamic myData = GetMyData();
foreach(dynamic d in myData.data)
{
   Console.WriteLine(d.name);
}
Run Code Online (Sandbox Code Playgroud)

我怎么能按字母顺序写出所有名字?如果我使用的东西就像List<MyClass>我会使用的那样myData.OrderBy(t => t.name),但是当我使用动态类型时,这似乎不起作用.

有关如何订购这些价值的任何建议?

.net c#

1
推荐指数
1
解决办法
495
查看次数

如何对具有ExpandoObject类型的对象应用扩展方法?

这是我的代码:

public static class DynamicExtensions

    public static void Add(this ExpandoObject obj, string path){
        dynamic _obj = obj;
        if (_obj == null) throw new ArgumentNullException("obj");
        _obj.path = path;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我以这种方式调用它时,我得到"'System.Dynamic.ExpandoObject'的错误不包含'Add'的定义":

dynamic obj = new ExpandoObject();
obj.Add("p1");
Run Code Online (Sandbox Code Playgroud)

怎么解决?

提前致谢!

c# extension-methods expandoobject

1
推荐指数
2
解决办法
2193
查看次数