dynamic casting?

南笙酒味 提交于 2019-12-13 14:16:13

问题


I need a way to cast an object to a type that is not know at compiler time.

something like this:

object obj;

public (type of obj) Obj
{
    get
    {
        return obj
    }
    set
    {
        obj = (type of obj)value;
    }
}

The only thing that is know is that obj is a value type.

I doubt that something like this would be possible. Just checking to see if someone has a clever way of doing it.


回答1:


This is not possible in C# 3.0, but if you could define a common interface that all of your objects implement, you could cast to that.

In C# 4.0 we will get the dynamic keyword that allows us to do Duck Typing.




回答2:


Well, you could do this with generics:

public class IAcceptValueTypes<T> where T: struct

private T obj;

public T Obj
{
    get { return obj; }
    set { obj = value; }
}

The generic constraint where T: struct will limit the acceptable type to value types.




回答3:


Such a cast would not actually do anything, because you're assigning at back to a variable with looser typing. Your best approach depends on what you want to do with the value type after "casting" it.

Options are:

  • Reflection
  • C# 4.0 dynamic typing.
  • A simple switch or if .. else based on the variable type.

Edit: using a generic class does not actually solve your problem if you know nothing about the type at compile time, but your example does not illustrate the actual usage of your class, so it may be that I'm misinterpreting your intentions. Something like this might actually be what you're looking for:

class MyClass<T> where T: struct
{
    T obj;

    public T Obj
    {
        get { return obj; }
        set { obj = value; }
    }
}

MyClass<int> test = new MyClass<int>();
test.Obj = 1;

The actual type definition is now outside your class, as a generic type parameter. Strictly speaking, the type is still static in that it is known at compile time however.




回答4:


I don't currently have Visual Studio in front of me to try out, but why don't you look up:

  • GetType
  • Convert.ChangeType



回答5:


why do you need such kind of casting?

  1. If number of types is limited you can implement generic version of your property.
  2. You can use the reflection to understand type of passed object and cast to this type.


来源:https://stackoverflow.com/questions/1437162/dynamic-casting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!