Dynamic cast at runtime

笑着哭i 提交于 2021-02-05 09:12:15

问题


Is there a way to dynamically cast at runtime like the following pseudo code:

foreach (DataRow row in table.Rows)
{
    foreach (DataColumn col in table.Columns)
    {
        if (row[col] != DBNull.Value)
        {
            Type type = col.DataType;

            type cellContent = (type)row[col]; //Pseudo-Code
        }
    }
}

I´ve been searching the web and not found anything. There´s object obj = Activator.CreateInstance(type);, but then I´m still stuck with an object and can´t use specific type methods with it. Also I need a cast of an existing object and not a new instance. I need to remove all EventHandlers from CellContent as in certain cases they cause a memory leak, example: Object type is IList[SerialNumberGridViewModel] and SerialNumberGridViewModel implements PropertyChanged-Handler which is causing a memory leak. Any idea? Is there a way to solve this issue?

I´ve already solved it in the above specific case, but a general method would be a lot better, as the program I´m working with is big and has a lot of memory leaks to be removed.


回答1:


No. You can't cast to any type that is unknown at compile time. However, c# does have a special keyword for declaring variables of a type that is unknown - it's dynamic.
You can think of it like a form of late binding - The actual type of the variable is determind at run time only.
When you declare a dynamic variable, c# compiler actually creates a variable of type object, but does not perform any type checking.

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time.
...
Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.




回答2:


Well I'll give it a try. The part about reflection is a bit confusing, but what I think you are looking for is the Dispose pattern.

Check: https://msdn.microsoft.com/en-us/library/ms244737.aspx

All the classes which would need cleanup code e.g. SerialNumberGridViewModel would implement IDisposable. From outside you would cast to IDisposable and just call Dispose(). Every object decides for itself what has to be done now e.g. remove Eventhandlers, etc. etc.

regards



来源:https://stackoverflow.com/questions/43068454/dynamic-cast-at-runtime

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