本文介绍了成员类型的设置在泛型类型方法的编译时引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类CommentComment和JobsComment,它们是从注释表派生的,它们都具有各自的residId和JobId respc.

我正在尝试使用功能将评论保存在发布方法中

I have two classes candidateComments and jobscomment derived from comment table both having individual candidateId and JobId respc.

I im trying to save the comments in a post method using function

public bool post(T model,Int id)
{

    //code to set common fields 
    //code to check which type using type of
    
    if(typeof(model)==typeof(candidatecomment))
    {
        model.candiateId=id;// i get error here as the model at compile time doesnt knw whether it is candidatecomment or job comment.
    }else
    {
        model.jobid =id
    }
}



有没有一种方法可以将编译器设置为在运行时推迟类型检查?



Is there a way i can set the compiler to postpone the type checking at runtime ??

推荐答案

public bool post(T model,Int id)
{
 
    //code to set common fields 
    //code to check which type using type of
    
    if(model is candidatecomment)
    {
        ((candidatecomment)model).candidateId = id;
    }else
    {
        ((jobcomment)model).jobid = id;
    }
}




要回答另一个问题,是的,有一种方法可以在运行时禁用类型检查,但是有点脏:




To answer your other question, yes, there is a way to disable type checking at runtime, but its a bit dirty:

public bool post(dynamic model,Int id)
{
 
    //code to set common fields 
    //code to check which type using type of
    
    if(model is candidatecomment)
    {
        model.candidateId = id;
    }else
    {
        model.jobid = id;
    }
}



关键字dynamic基本上意味着编译器将在运行时才检查数据的类型.这很脏,因为Intellisense无法在模型上运行(因此,键入模型.将不会显示提示菜单),并且您必须通过内存正确获取拼写和大写字母.我会避免这种情况,而应该选择顶部的那个.



The keyword dynamic basically means that the compiler will not check the type of the data until runtime. This is dirty because Intellisense won''t work on the model (so typing model. won''t bring up a hint menu), and you have to get the spelling and capitalization right by memory. I would avoid this in favor of the one on top.


这篇关于成员类型的设置在泛型类型方法的编译时引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 16:57