I use this in visual studio but the compiler claimed that h1 cannot be nested in legend element, but browser can render it anyway so i am confused
There are many things that browsers do that aren't required by the standards :-)
This page here (HTML4) specifies the legend keyword and states that it can contain inline elements, of which the headers are not a part. It does have other possibly useful ones such as big or strong.
In addition, the relevant page for H1 does not list legend as one of the items it's allowed to be contained within. You may also be able to use the id, class or style attributes of the legend to set the underlying textual properties.