C#自定义对象无效转换

时间:2017-01-19 10:39:37

标签: c# casting

我试图像下面那样投射我的物体:

public interface IObjectComparison
{
    object GetPropertyValue(string property);

}

public class MyObject : IObjectComparison
{
    public object GetPropertyValue(string property)
    {
        ...
        return (object)...;
    }
}

然后

MyObject mo = new MyObject();
IObjectComparison imo = (IObjectComparison) mo;

MyObject投射到IObjectComparison时,我收到了 InvalidCastException 。为什么?

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

你根本不需要施放。只需使用:

#include <stdlib.h>
#include <stdio.h>

#define nullptr (void *)0

struct S {
    void *content;
    struct S *next;
};
typedef struct S Stack;
Stack *createStack() {
    Stack *tmp = (Stack *) malloc(sizeof(Stack));

    tmp->content = nullptr;
    tmp->next    = nullptr;

    return tmp;
}

Stack *pushStack(Stack *ptr, void *content) {
    Stack *newStr = createStack();
    newStr->content = content;
    newStr->next = ptr;
    ptr = newStr;
    return (ptr);
}

Stack *popStack(Stack *ptr, void *value) {
    Stack *toDelete = ptr;
    value = ptr->content;
    ptr = ptr->next;
    free(toDelete);
    return (ptr);
}

Stack *stackHandle = nullptr;

void printStack(Stack *ptr) {
    int *element;
    int i;
    for(i=0; i <= 20; i++) {
        ptr = popStack(ptr, element);
        printf("%d ", *element);
    }
    printf("\n");
}

int main() {
    stackHandle = createStack();
    int i;
    for(i=0; i <= 21; i++) {
        stackHandle = pushStack(stackHandle, &i);
    }
    printStack(stackHandle);
}

答案 1 :(得分:0)

此代码可以正常工作:

public interface IObjectComparison
{
    object GetPropertyValue(string property);
}

public class MyObject : IObjectComparison
{
    public object GetPropertyValue(string property)
    {
        return new object();
    }
}

class Program
{
    static void Main()
    {
        MyObject mo = new MyObject();
        IObjectComparison imo = (IObjectComparison)mo;
    }

}